feat(resolver): add permission-associated cells

84158aa32cca6a8ce249eeefb07c5cc35a2acf1026dcc27af31205e459fc8b86
Associate shared cells with explicit permission owners so code can borrow
payload references through aliases while storage lifetime remains independent.
Functions pass authority explicitly, and lexical loans enforce shared and
exclusive access without runtime checks or hidden effects.

Extend cell syntax, type propagation, call checking, ownership analysis, and
storage validation. Support eligible non-Copy payloads, projected replacement,
and recursive nominal types. Migrate register-allocation flow topology and add
adversarial resolver coverage plus an executable cyclic structure proof.
Alexis Sellier committed ago 1 parent 80a2b616
CELL_PERMISSIONS added +180 -0
1 +
================
2 +
CELL PERMISSIONS
3 +
================
4 +
5 +
This document defines permission-associated cells. The words MUST, MUST NOT,
6 +
SHOULD, and MAY are normative.
7 +
8 +
TERMS
9 +
=====
10 +
11 +
A storage region controls the lifetime and reclamation of a cell's storage.
12 +
13 +
A permission owner is a non-Copy value. One explicit exclusive borrow of that
14 +
value backs one permission identity. A named permission region denotes that
15 +
identity. A permission controls access to all cells that have its identity.
16 +
It does not own or reclaim their storage.
17 +
18 +
A loan region is the lexical region of a payload reference and of the matching
19 +
borrow of the permission owner. Storage, permission, and loan regions are
20 +
separate regions.
21 +
22 +
An associated cell is a cell type that names a permission region. Every alias
23 +
of the cell has the same permission association.
24 +
25 +
TYPE AND CONSTRUCTION SYNTAX
26 +
============================
27 +
28 +
The associated cell type is:
29 +
30 +
    &'storage cell 'permission T
31 +
32 +
The first region is the storage region. The optional region after `cell` is
33 +
the permission region. Existing unassociated forms, such as `&cell T` and
34 +
`&'storage cell T`, keep their current meaning.
35 +
36 +
The associated construction form is:
37 +
38 +
    &cell 'permission place
39 +
40 +
`place` MUST be initialized and exclusively accessible when this expression
41 +
executes. Its storage region becomes the cell's storage region. The named
42 +
permission identity becomes the cell's permission association. Construction
43 +
MUST have the matching permission authority in scope.
44 +
45 +
An unassociated cell MAY provide value access when `T` is Copy. It MUST NOT
46 +
produce a shared or mutable reference to its payload.
47 +
48 +
PERMISSION AUTHORITY
49 +
====================
50 +
51 +
A lexical permission region MUST contain one explicit exclusive borrow of its
52 +
non-Copy owner. For example:
53 +
54 +
    let permission: 'permission = &mut owner in {
55 +
        // `permission` is the authority for `'permission`.
56 +
    }
57 +
58 +
A function that uses `'permission` in an associated cell type MUST also take
59 +
an explicit authority parameter of the form:
60 +
61 +
    permission: &'permission mut Owner
62 +
63 +
The function MUST use the same region in the cell type and the authority
64 +
parameter. Permission access is therefore an explicit call argument. The
65 +
language MUST NOT infer a transitive permission effect.
66 +
67 +
ACCESS AND LOANS
68 +
================
69 +
70 +
Direct Copy reads and whole-value writes through an associated cell require
71 +
available matching permission authority.
72 +
73 +
A payload reference MUST be created in an explicit lexical region block. The
74 +
same block MUST borrow the matching permission owner into the same loan
75 +
region.
76 +
77 +
For a shared payload reference, the block MUST borrow the permission owner
78 +
with `&`. Any number of shared payload references for that permission MAY be
79 +
live together. While one is live, mutation through every cell with that
80 +
permission MUST be rejected.
81 +
82 +
For a mutable payload reference, the block MUST borrow the permission owner
83 +
with `&mut`. While it is live, every other read, write, or payload borrow
84 +
through every cell with that permission MUST be rejected.
85 +
86 +
The payload reference MUST end at the lexical end of its loan region. It MUST
87 +
NOT escape the matching permission-owner borrow. It also MUST NOT outlive its
88 +
cell's storage region. Reclamation or reset of the storage region MUST remain
89 +
invalid while a payload reference into that storage is live. A payload loan
90 +
does not itself borrow the storage owner, so allocation that does not reclaim
91 +
or reset existing storage MAY continue.
92 +
93 +
Aliases, field extraction, assignment, substitution, and storage-region
94 +
shortening MUST preserve the permission association. If storage region
95 +
`'storage` is shortened to `'short`, the result is
96 +
`&'short cell 'permission T`; it is not relabeled to another permission.
97 +
Permission associations are invariant.
98 +
99 +
GENERICS AND CALLS
100 +
==================
101 +
102 +
A generic function MUST declare each permission region that occurs in an
103 +
associated cell parameter and MUST receive the matching explicit authority
104 +
parameter. Region inference and substitution MUST propagate the permission
105 +
association through cell types.
106 +
107 +
A call MUST use the same permission identity for an associated cell and its
108 +
authority argument. It MUST reject cross-permission access, relabeling, and
109 +
any call or callback that conflicts with a live loan. Two distinct permission
110 +
parameters in one signature MUST NOT map to the same actual permission
111 +
identity at a call.
112 +
113 +
After a payload reference is passed as an ordinary `&T` or `&mut T`, a helper
114 +
uses the ordinary reference rules. The helper does not need a cell permission
115 +
argument unless it also accesses an associated cell.
116 +
117 +
NON-COPY PAYLOADS
118 +
=================
119 +
120 +
An associated cell MAY contain a non-Copy payload only when that payload is
121 +
eligible for bulk discard under the existing ownership rules. Such a payload
122 +
MAY be borrowed by reference under the access and loan rules above.
123 +
124 +
An implicit payload value read MUST require Copy. A move of the payload or of
125 +
a payload field that would leave shared storage partly or wholly uninitialized
126 +
MUST be rejected.
127 +
128 +
Whole-value replacement is permitted. The operation MUST evaluate the new
129 +
value before it changes the cell. If evaluation fails, the cell MUST remain
130 +
unchanged. After successful evaluation, the operation MUST replace the old
131 +
value and bulk-discard the old value. It MUST NOT run a destructor.
132 +
133 +
Storage reclamation remains a bulk operation controlled only by the storage
134 +
region. Permission expiration does not reclaim storage. Freezing remains a
135 +
library-level state transition.
136 +
137 +
EXAMPLE
138 +
========
139 +
140 +
This example uses distinct storage, permission, and loan regions:
141 +
142 +
    record Permit {}
143 +
    record Item { value: u32 }
144 +
145 +
    fn addOne(item: &mut Item) {
146 +
        set item.value += 1;
147 +
    }
148 +
149 +
    fn update 'storage 'permission (
150 +
        item: &'storage cell 'permission Item,
151 +
        permission: &'permission mut Permit,
152 +
    ) {
153 +
        let authority: 'loan = &mut *permission,
154 +
            payload = &mut *item in {
155 +
            addOne(payload);
156 +
        }
157 +
    }
158 +
159 +
    fn example 'storage (storage: &Session 'storage) throws (AllocError) {
160 +
        let mut owner = Permit {};
161 +
        let permission: 'permission = &mut owner in {
162 +
            let place = try storage.new(Item { value: 0 });
163 +
            let item: &'storage cell 'permission Item =
164 +
                &cell 'permission *place;
165 +
            update(item, permission);
166 +
        }
167 +
    }
168 +
169 +
COMPILE-TIME AND RUNTIME CONTRACT
170 +
=================================
171 +
172 +
Permission identities, cell associations, and loan conflicts are compile-time
173 +
facts. They MUST NOT add garbage collection, runtime identity values, runtime
174 +
borrow checks, hidden arguments, hidden effects, or general alias analysis.
175 +
176 +
An associated cell MUST have the same pointer layout and runtime operations as
177 +
an unassociated cell. Permission metadata MUST NOT change emitted pointer
178 +
representation. This feature MUST NOT add destructors. Ordinary `&mut`,
179 +
`&cell`, field access, and `set` remain the access operations; the feature adds
180 +
no read or write block syntax.
compiler/radiance.rad +5 -5
43 43
/// Byte size of the five u32 fields in a single-file RV64 image header.
44 44
constant IMAGE_HEADER_SIZE: u32 = @sizeOf([u32; 5]);
45 45
46 46
/// AST arena size (64 MB) - retains parsed nodes throughout compilation.
47 47
constant TEMP_ARENA_SIZE: u32 = 67108864;
48 -
/// Per-function lowering and register-allocation arena size (16 MB).
49 -
constant FN_ARENA_SIZE: u32 = 16777216;
50 -
/// Main arena size (176 MB) - lives throughout compilation.
48 +
/// Per-function lowering and register-allocation arena size (24 MB).
49 +
constant FN_ARENA_SIZE: u32 = 25165824;
50 +
/// Main arena size (208 MB) - lives throughout compilation.
51 51
/// Used for: resolver data, types, symbols, global IL data, and codegen output.
52 -
constant MAIN_ARENA_SIZE: u32 = 184549376;
52 +
constant MAIN_ARENA_SIZE: u32 = 218103808;
53 53
54 54
/// AST storage arena.
55 55
static TEMP_ARENA: [u8; TEMP_ARENA_SIZE] = [0; TEMP_ARENA_SIZE];
56 56
/// Scratch storage reclaimed after each generated function.
57 57
static FN_ARENA: [u8; FN_ARENA_SIZE] = [0; FN_ARENA_SIZE];
816 816
    }
817 817
    let arrayLit = ast::synthNode(arena, ast::NodeValue::ArrayLit(elements));
818 818
819 819
    // Build: `&[...]`.
820 820
    let testsRef = ast::synthNode(arena, ast::NodeValue::AddressOf(ast::AddressOf {
821 -
        target: arrayLit, kind: ast::AddressKind::Shared,
821 +
        target: arrayLit, kind: ast::AddressKind::Shared, permission: nil,
822 822
    }));
823 823
824 824
    // Build: `testing::runAllTests(&[...])`.
825 825
    let runFn = synthScopeAccess(arena, &["testing", "runAllTests"]);
826 826
    let callArgs = ast::nodeSlice(arena, 1).append(testsRef, a);
lib/std/lang/ast.rad +6 -2
216 216
    },
217 217
    /// Shared cell pointer with value access to its payload.
218 218
    Cell {
219 219
        /// Storage lifetime and ownership class.
220 220
        class: PointerClass,
221 -
        /// Copy payload type.
221 +
        /// Optional compile-time permission region.
222 +
        permission: ?*Node,
223 +
        /// Payload type.
222 224
        payload: *Node,
223 225
    },
224 226
    /// Nominal type, points to identifier node.
225 227
    Nominal(*Node),
226 228
    /// Reference qualified by a lexical region.
277 279
export union AddressKind: Copy {
278 280
    /// Shared access to an immutable value.
279 281
    Shared,
280 282
    /// Exclusive access to a mutable value.
281 283
    Mutable,
282 -
    /// Shared access to a mutable Copy payload.
284 +
    /// Shared cell access to initialized payload storage.
283 285
    Cell,
284 286
}
285 287
286 288
/// Address-of expression metadata.
287 289
export record AddressOf: Copy {
288 290
    /// Target expression being referenced.
289 291
    target: *Node,
290 292
    /// Access provided by the resulting pointer.
291 293
    kind: AddressKind,
294 +
    /// Optional compile-time permission region for cell addresses.
295 +
    permission: ?*Node,
292 296
}
293 297
294 298
/// Return whether creating an address requires exclusive source access.
295 299
export fn isExclusiveAddress(address: AddressOf) -> bool {
296 300
    return address.kind <> AddressKind::Shared;
lib/std/lang/ast/printer.rad +21 -6
102 102
            return sexpr::list(a, head, &[sexpr::sym("mut"), toExpr(a, valueType)]) if mutable
103 103
                else sexpr::list(a, head, &[toExpr(a, valueType)]);
104 104
        }
105 105
        case super::TypeSig::Optional { valueType } =>
106 106
            return sexpr::list(a, "?", &[toExpr(a, valueType)]),
107 -
        case super::TypeSig::Cell { class, payload } =>
108 -
            return sexpr::list(a, pointerClassHead(class, "cell-ptr", "cell-ref", "unsafe-cell-ptr"), &[toExpr(a, payload)]),
107 +
        case super::TypeSig::Cell { class, permission, payload } => {
108 +
            let head = pointerClassHead(class, "cell-ptr", "cell-ref", "unsafe-cell-ptr");
109 +
            if let region = permission {
110 +
                return sexpr::list(a, head, &[toExpr(a, region), toExpr(a, payload)]);
111 +
            }
112 +
            return sexpr::list(a, head, &[toExpr(a, payload)]);
113 +
        }
109 114
        case super::TypeSig::Nominal(name) => return toExpr(a, name),
110 115
        case super::TypeSig::RegionRef { region, type } =>
111 116
            return sexpr::list(a, "region-ref", &[toExpr(a, region), toExpr(a, type)]),
112 117
        case super::TypeSig::Applied { name, regions } =>
113 118
            return sexpr::list(a, "apply", &[toExpr(a, name), sexpr::list(a, "regions", nodeListToExprs(a, regions))]),
304 309
            return sexpr::list(a, "[]", &[toExpr(a, container), toExpr(a, index)]),
305 310
        case super::NodeValue::FieldAccess(acc) =>
306 311
            return sexpr::list(a, ".", &[toExpr(a, acc.parent), toExpr(a, acc.child)]),
307 312
        case super::NodeValue::ScopeAccess(acc) =>
308 313
            return sexpr::list(a, "::", &[toExpr(a, acc.parent), toExpr(a, acc.child)]),
309 -
        case super::NodeValue::AddressOf(addr) =>
310 -
            return sexpr::list(a, "&cell", &[toExpr(a, addr.target)]) if addr.kind == super::AddressKind::Cell
311 -
                else sexpr::list(a, "&mut", &[toExpr(a, addr.target)]) if addr.kind == super::AddressKind::Mutable
312 -
                else sexpr::list(a, "&", &[toExpr(a, addr.target)]),
314 +
        case super::NodeValue::AddressOf(addr) => {
315 +
            if addr.kind == super::AddressKind::Cell {
316 +
                if let permission = addr.permission {
317 +
                    return sexpr::list(a, "&cell", &[
318 +
                        toExpr(a, permission),
319 +
                        toExpr(a, addr.target),
320 +
                    ]);
321 +
                }
322 +
                return sexpr::list(a, "&cell", &[toExpr(a, addr.target)]);
323 +
            }
324 +
            return sexpr::list(a, "&mut", &[toExpr(a, addr.target)])
325 +
                if addr.kind == super::AddressKind::Mutable
326 +
                else sexpr::list(a, "&", &[toExpr(a, addr.target)]);
327 +
        }
313 328
        case super::NodeValue::Deref(target) =>
314 329
            return sexpr::list(a, "deref", &[toExpr(a, target)]),
315 330
        case super::NodeValue::As(cast) =>
316 331
            return sexpr::list(a, "as", &[toExpr(a, cast.value), toExpr(a, cast.type)]),
317 332
        case super::NodeValue::ArrayLit(elems) =>
lib/std/lang/gen/regalloc/flow.rad +54 -26
2 2
3 3
use std::graph;
4 4
use std::lang::alloc;
5 5
use std::lang::il::published;
6 6
7 +
/// Zero-state owner for authority over one flow topology.
8 +
export record Permission {}
9 +
7 10
/// Stable block identity and private successor storage.
8 -
export opaque record Block: 's + Copy {
11 +
export opaque record Block: 'storage + 'permission + Copy {
9 12
    /// Graph capability identity.
10 -
    token: graph::Node 's,
13 +
    token: graph::Node 'storage,
11 14
    /// Block position in the function's dataflow tables.
12 15
    index: u32,
13 16
    /// Successors published when construction is complete.
14 -
    links: &'s cell &'s [Block 's],
17 +
    links: &'storage cell 'permission &'storage [Block 'storage 'permission],
15 18
}
16 19
17 20
/// Immutable topology whose storage belongs to the analysis session.
18 -
export opaque record Flow: 's + Copy {
21 +
export opaque record Flow: 'storage + 'permission + Copy {
19 22
    /// Shared authority for every block in the topology.
20 -
    frozen: graph::Frozen 's,
23 +
    frozen: graph::Frozen 'storage,
21 24
    /// Stable block handles in function order.
22 -
    blocks: &'s [Block 's],
25 +
    blocks: &'storage [Block 'storage 'permission],
23 26
}
24 27
25 28
/// Copy published successor topology into session-owned graph storage.
26 -
export fn snapshot 'input 's (blocks: &[published::Block 'input], storage: &Session 's)
27 -
    -> Flow 's throws (alloc::AllocError)
28 -
{
29 +
export fn snapshot 'input 'storage 'permission (
30 +
    blocks: &[published::Block 'input],
31 +
    storage: &Session 'storage,
32 +
    permission: &'permission mut Permission,
33 +
) -> Flow 'storage 'permission throws (alloc::AllocError) {
29 34
    let mut builder = try graph::new(storage);
30 -
    let none: [Block 's; 0] = [];
31 -
    let empty: &'s [Block 's] = try storage.copy(&none[..]);
35 +
    let none: [Block 'storage 'permission; 0] = [];
36 +
    let empty: &'storage [Block 'storage 'permission] = try storage.copy(&none[..]);
32 37
    if blocks.len == 0 {
33 -
        return Flow 's { frozen: try! graph::freeze(builder), blocks: empty };
38 +
        return Flow 'storage 'permission {
39 +
            frozen: try! graph::freeze(builder),
40 +
            blocks: empty,
41 +
        };
34 42
    }
35 -
    let first = try reserve(&mut builder, 0, empty, storage);
43 +
    let first = try reserve(&mut builder, 0, empty, storage, permission);
36 44
    let entries = try storage.fill(first, blocks.len);
37 45
    for i in 1..blocks.len {
38 -
        set entries[i] = try reserve(&mut builder, i, empty, storage);
46 +
        set entries[i] = try reserve(&mut builder, i, empty, storage, permission);
39 47
    }
40 48
    for block, i in blocks {
41 49
        let instructions = block.instructions;
42 50
        let mut links = empty;
43 51
        if instructions.len > 0 {
48 56
                    set successors[j] = entries[targets[j]];
49 57
                }
50 58
                set links = &successors[..];
51 59
            }
52 60
        }
53 -
        try! define(&mut builder, entries[i], links);
61 +
        try! define(&mut builder, entries[i], links, permission);
54 62
    }
55 -
    return Flow 's { frozen: try! graph::freeze(builder), blocks: &entries[..] };
63 +
    return Flow 'storage 'permission {
64 +
        frozen: try! graph::freeze(builder),
65 +
        blocks: &entries[..],
66 +
    };
56 67
}
57 68
58 69
/// Reserve a block before its outgoing links are known.
59 -
fn reserve 's (builder: &mut graph::Builder 's, index: u32, empty: &'s [Block 's], storage: &Session 's)
60 -
    -> Block 's throws (alloc::AllocError)
61 -
{
70 +
fn reserve 'storage 'permission (
71 +
    builder: &mut graph::Builder 'storage,
72 +
    index: u32,
73 +
    empty: &'storage [Block 'storage 'permission],
74 +
    storage: &Session 'storage,
75 +
    permission: &'permission mut Permission,
76 +
) -> Block 'storage 'permission throws (alloc::AllocError) {
62 77
    let links = try storage.new(empty);
63 78
    let token = try graph::reserve(builder, storage);
64 -
    return Block 's { token, index, links: &cell *links };
79 +
    return Block 'storage 'permission {
80 +
        token,
81 +
        index,
82 +
        links: &cell 'permission *links,
83 +
    };
65 84
}
66 85
67 86
/// Complete a block after all successors have been checked.
68 -
fn define 's (builder: &mut graph::Builder 's, block: Block 's, links: &'s [Block 's])
69 -
    throws (graph::Error)
70 -
{
87 +
fn define 'storage 'permission (
88 +
    builder: &mut graph::Builder 'storage,
89 +
    block: Block 'storage 'permission,
90 +
    links: &'storage [Block 'storage 'permission],
91 +
    permission: &'permission mut Permission,
92 +
) throws (graph::Error) {
71 93
    try graph::check(builder, block.token);
72 94
    for successor in links {
73 95
        try graph::check(builder, successor.token);
74 96
    }
75 97
    set *block.links = links;
76 98
    try graph::complete(builder, block.token);
77 99
}
78 100
79 101
/// Borrow the successors of a published block.
80 -
export fn successors 's (flow: &Flow 's, index: u32) -> &'s [Block 's] {
102 +
export fn successors 'storage 'permission (
103 +
    flow: &Flow 'storage 'permission,
104 +
    index: u32,
105 +
    permission: &'permission mut Permission,
106 +
) -> &'storage [Block 'storage 'permission] {
81 107
    let block = flow.blocks[index];
82 108
    try! graph::checkFrozen(&flow.frozen, block.token);
83 -
    return *block.links;
109 +
    let authority: 'loan = &*permission, links = &*block.links in {
110 +
        return *links;
111 +
    }
84 112
}
85 113
86 114
/// Return the dataflow table position retained by a block identity.
87 -
export fn index 's (block: Block 's) -> u32 {
115 +
export fn index 'storage 'permission (block: Block 'storage 'permission) -> u32 {
88 116
    return block.index;
89 117
}
lib/std/lang/gen/regalloc/liveness.rad +9 -5
91 91
    // Compute local defs and uses for each block.
92 92
    for b in 0..blockCount {
93 93
        let block = &blocks[b];
94 94
        computeLocalDefsUses(block.params, block.instructions, &mut defs[b * words..(b + 1) * words], &mut uses[b * words..(b + 1) * words]);
95 95
    }
96 -
    let topology = try flow::snapshot(blocks, storage);
97 -
    propagateLiveness(&topology, blockCount, liveIn, liveOut, defs, uses, words);
96 +
    let mut owner = flow::Permission {};
97 +
    let permission: 'permission = &mut owner in {
98 +
        let topology = try flow::snapshot(blocks, storage, permission);
99 +
        propagateLiveness(&topology, permission, blockCount, liveIn, liveOut, defs, uses, words);
100 +
    }
98 101
    return LiveInfo 'scratch { liveIn: &liveIn[..], liveOut: &liveOut[..], defs: &defs[..], uses: &uses[..], words, blockCount, maxReg };
99 102
}
100 103
101 104
/// Propagate successor uses until every block's live-in row is stable.
102 -
fn propagateLiveness 'scratch (
103 -
    topology: &flow::Flow 'scratch,
105 +
fn propagateLiveness 'scratch 'permission (
106 +
    topology: &flow::Flow 'scratch 'permission,
107 +
    permission: &'permission mut flow::Permission,
104 108
    blockCount: u32,
105 109
    liveIn: &mut [u32],
106 110
    liveOut: &mut [u32],
107 111
    defs: &[u32],
108 112
    uses: &[u32],
117 121
        // Process blocks in reverse order (approximates post-order).
118 122
        let mut b = blockCount;
119 123
        while b > 0 {
120 124
            set b -= 1;
121 125
            // Add successor live-in sets directly to this block's live-out set.
122 -
            for successor in flow::successors(topology, b) {
126 +
            for successor in flow::successors(topology, b, permission) {
123 127
                unionBlockLiveIn(flow::index(successor), liveIn, words, &mut liveOut[b * words..(b + 1) * words]);
124 128
            }
125 129
126 130
            if computeAndUpdateLiveIn(&mut liveIn[b * words..(b + 1) * words], &liveOut[b * words..(b + 1) * words], &defs[b * words..(b + 1) * words], &uses[b * words..(b + 1) * words]) {
127 131
                set changed = true;
lib/std/lang/gen/regalloc/liveness/tests.rad +28 -21
47 47
        return try assign::assign(&view, live, spills, config, storage);
48 48
    }
49 49
}
50 50
51 51
/// Publish CFG fixture inputs outside the graph allocation test arena.
52 -
unsafe fn snapshot 'scratch (blocks: &[il::Block], storage: &Session 'scratch)
53 -
    -> flow::Flow 'scratch throws (alloc::AllocError)
54 -
{
52 +
unsafe fn snapshot 'scratch 'permission (
53 +
    blocks: &[il::Block],
54 +
    storage: &Session 'scratch,
55 +
    permission: &'permission mut flow::Permission,
56 +
) -> flow::Flow 'scratch 'permission throws (alloc::AllocError) {
55 57
    let function = il::Fn { name: "topology", params: &[], returnType: il::Type::W64,
56 58
        isExtern: false, isLeaf: true, blocks: blocks as *unsafe [il::Block] };
57 59
    static DATA: [u8; 4096] = [0; 4096];
58 60
    let mut arena = alloc::new(&mut DATA[..]);
59 61
    use arena as inputs in {
60 62
        let view = try published::publish(&function, &inputs);
61 -
        return try flow::snapshot(view.blocks, storage);
63 +
        return try flow::snapshot(view.blocks, storage, permission);
62 64
    }
63 65
}
64 66
65 67
/// Frozen topology owns successor tables and preserves cyclic block identities.
66 68
@test unsafe fn testOwnedFlowSnapshot() throws (testing::TestError) {
69 71
        defaultArgs: &mut [], cases: &mut cases[..] }];
70 72
    let mut second = [il::Instr::Jmp { target: 0, args: &mut [] }];
71 73
    let blocks = [block("first", &mut first[..]), block("second", &mut second[..])];
72 74
    static DATA: [u8; 2048] = [0; 2048];
73 75
    let mut arena = alloc::new(&mut DATA[..]);
76 +
    let mut owner = flow::Permission {};
74 77
    use arena as storage in {
75 -
        let frozen = try! snapshot(&blocks[..], &storage);
76 -
        set cases[0].target = 0;
77 -
        set first[0] = il::Instr::Ret { val: il::Val::Imm(0) };
78 -
        set second[0] = il::Instr::Ret { val: il::Val::Imm(0) };
79 -
        let successors = flow::successors(&frozen, 0);
80 -
        assert successors.len == 2;
81 -
        assert flow::index(successors[0]) == 0;
82 -
        assert flow::index(successors[1]) == 1;
83 -
        let back = flow::successors(&frozen, 1);
84 -
        assert back.len == 1 and back[0] == successors[0];
78 +
        let permission: 'permission = &mut owner in {
79 +
            let frozen = try! snapshot(&blocks[..], &storage, permission);
80 +
            set cases[0].target = 0;
81 +
            set first[0] = il::Instr::Ret { val: il::Val::Imm(0) };
82 +
            set second[0] = il::Instr::Ret { val: il::Val::Imm(0) };
83 +
            let successors = flow::successors(&frozen, 0, permission);
84 +
            assert successors.len == 2;
85 +
            assert flow::index(successors[0]) == 0;
86 +
            assert flow::index(successors[1]) == 1;
87 +
            let back = flow::successors(&frozen, 1, permission);
88 +
            assert back.len == 1 and back[0] == successors[0];
89 +
        }
85 90
    }
86 91
    alloc::reset(&mut arena);
87 92
    assert alloc::used(&arena) == 0;
88 93
}
89 94
90 -
91 95
/// Every incomplete allocation stage reports failure and permits arena disposal.
92 96
@test unsafe fn testFlowAllocationFailure() throws (testing::TestError) {
93 97
    let mut instructions = [il::Instr::Jmp { target: 0, args: &mut [] }];
94 98
    let blocks = [block("loop", &mut instructions[..])];
95 99
    let mut succeeded = false;
96 100
    for capacity in 0..257 {
97 101
        static DATA: [u8; 256] = [0; 256];
98 102
        let mut arena = alloc::new(&mut DATA[..capacity]);
103 +
        let mut owner = flow::Permission {};
99 104
        use arena as storage in {
100 -
            if let frozen = try? snapshot(&blocks[..], &storage) {
101 -
                let links = flow::successors(&frozen, 0);
102 -
                assert links.len == 1 and flow::index(links[0]) == 0;
103 -
                set succeeded = true;
104 -
            } else {
105 -
                assert not succeeded;
105 +
            let permission: 'permission = &mut owner in {
106 +
                if let frozen = try? snapshot(&blocks[..], &storage, permission) {
107 +
                    let links = flow::successors(&frozen, 0, permission);
108 +
                    assert links.len == 1 and flow::index(links[0]) == 0;
109 +
                    set succeeded = true;
110 +
                } else {
111 +
                    assert not succeeded;
112 +
                }
106 113
            }
107 114
        }
108 115
        alloc::reset(&mut arena);
109 116
        assert alloc::used(&arena) == 0;
110 117
    }
lib/std/lang/parser.rad +27 -8
480 480
            let value = try parseUnaryExpr(p);
481 481
            return node(p, ast::NodeValue::Deref(value));
482 482
        }
483 483
        case scanner::TokenKind::Amp => {
484 484
            advance(p);
485 -
            let kind = parseAddressKind(p);
486 -
            let target = try parseUnaryExpr(p);
487 -
            return node(p, ast::NodeValue::AddressOf({ target, kind }));
485 +
            return try parseAddressOf(p);
488 486
        }
489 487
        else => {
490 488
            return try parsePrimary(p);
491 489
        }
492 490
    }
502 500
        return ast::AddressKind::Cell;
503 501
    }
504 502
    return ast::AddressKind::Shared;
505 503
}
506 504
505 +
/// Parse an address after its `&`, including cell-only permission metadata.
506 +
unsafe fn parseAddressOf 'pool (p: &mut Parser 'pool) -> *ast::Node throws (ParseError) {
507 +
    let kind = parseAddressKind(p);
508 +
    let mut permission: ?*ast::Node = nil;
509 +
    if kind == ast::AddressKind::Cell and check(p, scanner::TokenKind::Region) {
510 +
        set permission = try parseRegion(p);
511 +
    }
512 +
    let target = try parseUnaryExpr(p);
513 +
    return node(p, ast::NodeValue::AddressOf(
514 +
        ast::AddressOf { target, kind, permission }
515 +
    ));
516 +
}
517 +
507 518
/// Find the operator info for a token if it has precedence greater than the
508 519
/// given minimum.
509 520
fn findNextOp(kind: scanner::TokenKind, minPrec: i32) -> ?OpInfo {
510 521
    if let opInfo = getOpInfo(kind) {
511 522
        if opInfo.prec > minPrec {
1657 1668
    let mut region = node(p, ast::NodeValue::Region { name: regionName, parent: nil });
1658 1669
    let mut bindings = ast::nodeSlice(p.arena, 4);
1659 1670
    loop {
1660 1671
        try expect(p, scanner::TokenKind::Equal, "expected `=` after region binding");
1661 1672
        try expect(p, scanner::TokenKind::Amp, "expected `&` before borrowed place");
1662 -
        let kind = parseAddressKind(p);
1663 -
        let target = try parseUnaryExpr(p);
1664 -
        let value = node(p, ast::NodeValue::AddressOf({ target, kind }));
1673 +
        let value = try parseAddressOf(p);
1665 1674
        bindings.append(node(p, ast::NodeValue::RegionBinding({ label: binding, value })), p.allocator);
1666 1675
        if not consume(p, scanner::TokenKind::Comma) {
1667 1676
            break;
1668 1677
        }
1669 1678
        set binding = try parseIdent(p, "expected region binding name");
1697 1706
1698 1707
/// Parse an allocation session with an implicit exclusive source borrow.
1699 1708
unsafe fn parseSessionBlock 'pool (p: &mut Parser 'pool) -> *ast::Node throws (ParseError) {
1700 1709
    try expect(p, scanner::TokenKind::Use, "expected `use`");
1701 1710
    let target = try parseUnaryExpr(p);
1702 -
    let value = node(p, ast::NodeValue::AddressOf({ target, kind: ast::AddressKind::Mutable }));
1711 +
    let value = node(p, ast::NodeValue::AddressOf(ast::AddressOf {
1712 +
        target,
1713 +
        kind: ast::AddressKind::Mutable,
1714 +
        permission: nil,
1715 +
    }));
1703 1716
    try expect(p, scanner::TokenKind::As, "expected `as` after allocation source");
1704 1717
    let binding = try parseIdent(p, "expected allocation binding after `as`");
1705 1718
    let region = sessionRegion(p, binding);
1706 1719
    try expect(p, scanner::TokenKind::In, "expected `in` after allocation binding");
1707 1720
    let bindings = ast::nodeSlice(p.arena, 1).append(
2119 2132
    p: &mut Parser 'pool,
2120 2133
    class: ast::PointerClass,
2121 2134
) -> *ast::Node throws (ParseError) {
2122 2135
    if check(p, scanner::TokenKind::Ident) and mem::eq(p.current.source, "cell") {
2123 2136
        advance(p);
2137 +
        let mut permission: ?*ast::Node = nil;
2138 +
        if check(p, scanner::TokenKind::Region) {
2139 +
            set permission = try parseRegion(p);
2140 +
        }
2124 2141
        let payload = try parseType(p);
2125 -
        return node(p, ast::NodeValue::TypeSig(ast::TypeSig::Cell { class, payload }));
2142 +
        return node(p, ast::NodeValue::TypeSig(
2143 +
            ast::TypeSig::Cell { class, permission, payload }
2144 +
        ));
2126 2145
    }
2127 2146
    let mutable = consume(p, scanner::TokenKind::Mut);
2128 2147
2129 2148
    if consume(p, scanner::TokenKind::LBracket) {
2130 2149
        let itemType = try parseType(p);
lib/std/lang/parser/tests.rad +94 -13
2324 2324
@test unsafe fn testParseRefs() throws (testing::TestError) {
2325 2325
    {
2326 2326
        let expr = try! parseExprStr("&cell obj.field");
2327 2327
        let case ast::NodeValue::AddressOf(address) = expr.value
2328 2328
            else throw testing::TestError::Failed;
2329 -
        try testing::expect(address.kind == ast::AddressKind::Cell);
2329 +
        try testing::expect(
2330 +
            address.kind == ast::AddressKind::Cell and address.permission == nil
2331 +
        );
2332 +
        let case ast::NodeValue::FieldAccess(access) = address.target.value
2333 +
            else throw testing::TestError::Failed;
2334 +
        try expectIdent(access.parent, "obj");
2335 +
        try expectIdent(access.child, "field");
2336 +
    }
2337 +
    {
2338 +
        let expr = try! parseExprStr("&cell 'permission obj.field");
2339 +
        let case ast::NodeValue::AddressOf(address) = expr.value
2340 +
            else throw testing::TestError::Failed;
2341 +
        let permission = address.permission else throw testing::TestError::Failed;
2342 +
        let case ast::NodeValue::Region { name, parent: nil } = permission.value
2343 +
            else throw testing::TestError::Failed;
2344 +
        try testing::expect(
2345 +
            address.kind == ast::AddressKind::Cell and mem::eq(name, "'permission")
2346 +
        );
2330 2347
        let case ast::NodeValue::FieldAccess(access) = address.target.value
2331 2348
            else throw testing::TestError::Failed;
2332 2349
        try expectIdent(access.parent, "obj");
2333 2350
        try expectIdent(access.child, "field");
2334 2351
    }
2335 2352
    {
2336 2353
        let refExpr = try! parseExprStr("&foo");
2337 2354
        let case ast::NodeValue::AddressOf(refNode) = refExpr.value
2338 2355
            else throw testing::TestError::Failed;
2339 -
        try testing::expect(refNode.kind == ast::AddressKind::Shared);
2356 +
        try testing::expect(
2357 +
            refNode.kind == ast::AddressKind::Shared and refNode.permission == nil
2358 +
        );
2340 2359
        try expectIdent(refNode.target, "foo");
2341 2360
    }
2342 2361
    {
2343 2362
        let mutRefExpr = try! parseExprStr("&mut bar");
2344 2363
        let case ast::NodeValue::AddressOf(mutRefNode) = mutRefExpr.value
2345 2364
            else throw testing::TestError::Failed;
2346 -
        try testing::expect(mutRefNode.kind == ast::AddressKind::Mutable);
2365 +
        try testing::expect(
2366 +
            mutRefNode.kind == ast::AddressKind::Mutable and mutRefNode.permission == nil
2367 +
        );
2347 2368
        try expectIdent(mutRefNode.target, "bar");
2348 2369
    }
2349 2370
    {
2350 2371
        let refFieldExpr = try! parseExprStr("&obj.field");
2351 2372
        let case ast::NodeValue::AddressOf(refFieldNode) = refFieldExpr.value
2352 2373
            else throw testing::TestError::Failed;
2353 -
        try testing::expect(refFieldNode.kind == ast::AddressKind::Shared);
2374 +
        try testing::expect(
2375 +
            refFieldNode.kind == ast::AddressKind::Shared and refFieldNode.permission == nil
2376 +
        );
2354 2377
        let case ast::NodeValue::FieldAccess(access) = refFieldNode.target.value
2355 2378
            else throw testing::TestError::Failed;
2356 2379
        try expectIdent(access.parent, "obj");
2357 2380
        try expectIdent(access.child, "field");
2358 2381
    }
2359 2382
    {
2360 2383
        let mutRefFieldExpr = try! parseExprStr("&mut obj.field");
2361 2384
        let case ast::NodeValue::AddressOf(mutRefFieldNode) = mutRefFieldExpr.value
2362 2385
            else throw testing::TestError::Failed;
2363 -
        try testing::expect(mutRefFieldNode.kind == ast::AddressKind::Mutable);
2386 +
        try testing::expect(
2387 +
            mutRefFieldNode.kind == ast::AddressKind::Mutable
2388 +
            and mutRefFieldNode.permission == nil
2389 +
        );
2364 2390
        let case ast::NodeValue::FieldAccess(access) = mutRefFieldNode.target.value
2365 2391
            else throw testing::TestError::Failed;
2366 2392
        try expectIdent(access.parent, "obj");
2367 2393
        try expectIdent(access.child, "field");
2368 2394
    }
2395 +
    for source in ["&'permission obj.field", "&mut 'permission obj.field"] {
2396 +
        let parsed = try? parseExprStr(source);
2397 +
        try testing::expect(parsed == nil);
2398 +
    }
2369 2399
}
2370 2400
2371 2401
/// Test unary operator precedence relative to binary and postfix expressions.
2372 2402
@test unsafe fn testParseUnaryPrecedence() throws (testing::TestError) {
2373 2403
    {
3186 3216
    let case ast::NodeValue::RegionBinding(arenaBinding) = arenaBindings[0].value
3187 3217
        else throw testing::TestError::Failed;
3188 3218
    let arenaLabel = arenaBinding.label else throw testing::TestError::Failed;
3189 3219
    let case ast::NodeValue::Ident(arenaLabelName) = arenaLabel.value
3190 3220
        else throw testing::TestError::Failed;
3191 -
    let case ast::NodeValue::AddressOf({ target: arenaTarget, kind: ast::AddressKind::Mutable }) = arenaBinding.value.value
3221 +
    let case ast::NodeValue::AddressOf({
3222 +
        target: arenaTarget, kind: ast::AddressKind::Mutable, permission: nil,
3223 +
    }) = arenaBinding.value.value
3192 3224
        else throw testing::TestError::Failed;
3193 3225
    let case ast::NodeValue::Ident(arenaTargetName) = arenaTarget.value
3194 3226
        else throw testing::TestError::Failed;
3195 3227
    try testing::expect(
3196 3228
        arenaSession and arenaBindings.len == 1
3276 3308
}
3277 3309
3278 3310
/// Cell qualifiers retain pointer ownership and payload syntax.
3279 3311
@test unsafe fn testCellPointerType() throws (testing::TestError) {
3280 3312
    let root = try! parseTypeStr("*cell u32");
3281 -
    let case ast::NodeValue::TypeSig(ast::TypeSig::Cell { class, payload }) = root.value
3282 -
        else throw testing::TestError::Failed;
3283 -
    try testing::expect(class == ast::PointerClass::Owned);
3313 +
    let case ast::NodeValue::TypeSig(ast::TypeSig::Cell {
3314 +
        class, payload, permission,
3315 +
    }) = root.value else throw testing::TestError::Failed;
3316 +
    try testing::expect(class == ast::PointerClass::Owned and permission == nil);
3284 3317
    let case ast::NodeValue::TypeSig(ast::TypeSig::Integer { width: 4, .. }) = payload.value
3285 3318
        else throw testing::TestError::Failed;
3319 +
3320 +
    let ownedAssociated = try! parseTypeStr("*cell 'permission u32");
3321 +
    let case ast::NodeValue::TypeSig(ast::TypeSig::Cell {
3322 +
        class: ownedClass, payload: ownedPayload, permission: ownedPermission,
3323 +
    }) = ownedAssociated.value else throw testing::TestError::Failed;
3324 +
    let ownedPermissionRegion = ownedPermission else throw testing::TestError::Failed;
3325 +
    let case ast::NodeValue::Region { name: ownedPermissionName, parent: nil } =
3326 +
        ownedPermissionRegion.value
3327 +
        else throw testing::TestError::Failed;
3328 +
    let case ast::NodeValue::TypeSig(ast::TypeSig::Integer { width: 4, .. }) =
3329 +
        ownedPayload.value
3330 +
        else throw testing::TestError::Failed;
3331 +
    try testing::expect(
3332 +
        ownedClass == ast::PointerClass::Owned
3333 +
        and mem::eq(ownedPermissionName, "'permission")
3334 +
    );
3335 +
3286 3336
    let borrowed = try! parseTypeStr("&'r cell Pair 's");
3287 3337
    let case ast::NodeValue::TypeSig(ast::TypeSig::RegionRef { type, .. }) = borrowed.value
3288 3338
        else throw testing::TestError::Failed;
3289 -
    let case ast::NodeValue::TypeSig(ast::TypeSig::Cell { class: refClass, payload: inner }) = type.value
3290 -
        else throw testing::TestError::Failed;
3291 -
    try testing::expect(refClass == ast::PointerClass::Ref);
3339 +
    let case ast::NodeValue::TypeSig(ast::TypeSig::Cell {
3340 +
        class: refClass, payload: inner, permission: refPermission,
3341 +
    }) = type.value else throw testing::TestError::Failed;
3342 +
    try testing::expect(refClass == ast::PointerClass::Ref and refPermission == nil);
3292 3343
    let case ast::NodeValue::TypeSig(ast::TypeSig::Applied { regions, .. }) = inner.value
3293 3344
        else throw testing::TestError::Failed;
3294 3345
    try testing::expect(regions.len == 1);
3295 -
}
3296 3346
3347 +
    let associated = try! parseTypeStr("&'storage cell 'permission Pair 'payload");
3348 +
    let case ast::NodeValue::TypeSig(ast::TypeSig::RegionRef {
3349 +
        region: storage, type: associatedType,
3350 +
    }) = associated.value else throw testing::TestError::Failed;
3351 +
    let case ast::NodeValue::Region { name: storageName, parent: nil } = storage.value
3352 +
        else throw testing::TestError::Failed;
3353 +
    let case ast::NodeValue::TypeSig(ast::TypeSig::Cell {
3354 +
        class: associatedClass,
3355 +
        payload: associatedPayload,
3356 +
        permission: associatedPermission,
3357 +
    }) = associatedType.value else throw testing::TestError::Failed;
3358 +
    let permissionRegion = associatedPermission else throw testing::TestError::Failed;
3359 +
    let case ast::NodeValue::Region { name: permissionName, parent: nil } =
3360 +
        permissionRegion.value
3361 +
        else throw testing::TestError::Failed;
3362 +
    let case ast::NodeValue::TypeSig(ast::TypeSig::Applied {
3363 +
        name: payloadName, regions: payloadRegions,
3364 +
    }) = associatedPayload.value else throw testing::TestError::Failed;
3365 +
    try expectIdent(payloadName, "Pair");
3366 +
    try testing::expect(payloadRegions.len == 1);
3367 +
    let case ast::NodeValue::Region { name: payloadRegionName, parent: nil } =
3368 +
        payloadRegions[0].value
3369 +
        else throw testing::TestError::Failed;
3370 +
    try testing::expect(
3371 +
        associatedClass == ast::PointerClass::Ref
3372 +
        and mem::eq(storageName, "'storage")
3373 +
        and mem::eq(permissionName, "'permission")
3374 +
        and mem::eq(payloadRegionName, "'payload")
3375 +
    );
3376 +
3377 +
}
3297 3378
3298 3379
/// Measure committed storage for a statement after an existing node.
3299 3380
unsafe fn statementStorageUsed(source: *[u8]) -> u32 {
3300 3381
    let mut arena = ast::nodeArena(&mut ARENA_STORAGE[..]);
3301 3382
    ast::allocNode(&mut arena, ast::Span { offset: 0, length: 0 }, ast::NodeValue::Bool(true));
lib/std/lang/resolver.rad +1479 -143
38 38
export constant ANALYZE_EXPR_FN_NAME: *[u8] = "__expr__";
39 39
/// Synthetic function name used when wrapping a block for analysis.
40 40
export constant ANALYZE_BLOCK_FN_NAME: *[u8] = "__block__";
41 41
42 42
/// Maximum number of symbols stored within a module scope.
43 -
export constant MAX_MODULE_SYMBOLS: u32 = 512;
43 +
export constant MAX_MODULE_SYMBOLS: u32 = 528;
44 44
/// Maximum number of symbols stored within a local scope.
45 45
export constant MAX_LOCAL_SYMBOLS: u32 = 32;
46 46
/// Maximum function parameters.
47 47
export constant MAX_FN_PARAMS: u32 = 8;
48 48
/// Maximum function thrown types.
189 189
    /// Module that can access the representation, or `nil` for public fields.
190 190
    privateModule: ?u16,
191 191
    /// Region parameters of the source declaration.
192 192
    regions: ?*RegionScope,
193 193
    /// Exact region arguments, if this is an applied type.
194 -
    application: ?*unsafe NominalApplication,
194 +
    application: ?*unsafe mut NominalApplication,
195 195
    fields: *unsafe [RecordField],
196 196
    labeled: bool,
197 197
    /// Shared layout of the source declaration.
198 198
    layout: *Layout,
199 199
    /// Whether the declaration explicitly carries the `Once` marker.
205 205
/// Union nominal type.
206 206
export record UnionType: Copy {
207 207
    /// Region parameters of the source declaration.
208 208
    regions: ?*RegionScope,
209 209
    /// Exact region arguments, if this is an applied type.
210 -
    application: ?*unsafe NominalApplication,
210 +
    application: ?*unsafe mut NominalApplication,
211 211
    variants: *unsafe [UnionVariant],
212 212
    /// Shared layout of the source declaration.
213 213
    layout: *Layout,
214 214
    /// Cached payload offset within the union aggregate.
215 215
    valOffset: u32,
227 227
    /// Stores the declaration node for lazy resolution.
228 228
    Placeholder(*ast::Node),
229 229
    /// Declaration whose value layout is under analysis.
230 230
    Resolving(*ast::Node),
231 231
    /// Applied type whose field or variant view is not yet resolved.
232 -
    Application(*unsafe NominalApplication),
232 +
    Application(*unsafe mut NominalApplication),
233 233
    Record(RecordType),
234 234
    Union(UnionType),
235 235
}
236 236
237 237
/// Coercion plan, when coercion from one type to another.
328 328
    Nil, Undefined, Int,
329 329
    /// Primitive types.
330 330
    Void, Opaque, Never, Bool,
331 331
    /// Integer types.
332 332
    U8, U16, U32, U64, I8, I16, I32, I64,
333 -
    /// Shared cell pointer with value access to a Copy payload.
333 +
    /// Shared cell pointer with controlled payload access.
334 334
    Cell {
335 335
        /// Storage lifetime and ownership class.
336 336
        class: types::PointerClass,
337 +
        /// Optional compile-time permission region.
338 +
        permission: ?*unsafe types::Region,
337 339
        /// Payload type, preserved by all writes.
338 340
        payload: *Type,
339 341
    },
340 342
    /// Affine allocation interface retained by a lexical region.
341 343
    Session(*unsafe types::Region),
694 696
    RegionEscape(*[u8]),
695 697
    /// A session requires one exclusive borrow of an allocation trait implementer.
696 698
    InvalidSessionSource,
697 699
    /// Allocation requires a value that can be discarded without destruction.
698 700
    InvalidAllocationValue,
699 -
    /// Cell payload is not a storable plain Copy value.
701 +
    /// Cell payload does not satisfy storage and ownership requirements.
700 702
    InvalidCellPayload,
703 +
    /// Cell payload access lacks matching lexical permission authority.
704 +
    CellPermissionRequired(*[u8]),
701 705
    /// The allocated value has an invalid or overflowing layout.
702 706
    InvalidAllocationLayout,
703 707
    /// A compiler-known allocation trait method has an invalid signature.
704 708
    InvalidAllocationRuntime,
705 709
    /// The function has too many distinct full-region projections.
927 931
    Place,
928 932
    /// Evaluate a place prefix after checking the complete place.
929 933
    Locate,
930 934
}
931 935
936 +
/// Region role sought during compile-time type traversal.
937 +
union RegionTypeRole: Copy {
938 +
    /// Compile-time identity associated with a cell payload.
939 +
    CellPermission,
940 +
    /// Storage reference that can carry a regional borrow.
941 +
    Reference,
942 +
    /// Interior storage that can retain a reference after a call returns.
943 +
    Retention,
944 +
    /// Region dependencies that must cover a destination.
945 +
    StorageValidation,
946 +
    /// Named storage retained by a value.
947 +
    StoragePresence,
948 +
}
949 +
932 950
/// Consumption rule for a tracked move-only binding.
933 951
union BindingUse: Copy {
934 952
    /// The binding can be consumed at most once.
935 953
    Affine,
936 954
    /// The binding must be consumed exactly once.
973 991
    /// Number of initialized field indices.
974 992
    len: u32,
975 993
    /// Whether further projections can identify distinct storage.
976 994
    precise: bool,
977 995
}
978 -
979 996
/// A reference binding that protects its source for one lexical scope.
980 997
record LocalLoan: Copy {
981 998
    /// Local symbol that provides access, or nil for a pending call argument.
982 999
    binding: ?*unsafe mut Symbol,
983 1000
    /// Storage retained by the reference.
984 1001
    place: BorrowPlace,
985 1002
    /// Whether other reads of the source are excluded.
986 1003
    exclusive: bool,
1004 +
    /// Permission identity protected independently of the source place.
1005 +
    permission: ?*unsafe types::Region,
1006 +
    /// Named region that owns associated cell storage, when one exists.
1007 +
    storage: ?*unsafe types::Region,
987 1008
}
988 1009
989 1010
/// Argument metadata retained during call-scoped conflict checks.
990 1011
record CallArgument: Copy {
991 1012
    /// Receiver or explicit argument expression.
992 1013
    node: *ast::Node,
993 1014
    /// Whether overlapping argument access is excluded.
994 1015
    exclusive: bool,
995 1016
}
996 -
997 1017
/// Function-local exact-use checker state.
998 1018
/// Read loop arrays only at indices below `loopDepth`.
999 1019
/// `enterLinearLoop` initializes each slot before it increases `loopDepth`.
1000 1020
record LinearChecker: 'arena + 'checking where 'arena: 'checking {
1001 1021
    /// Resolver that owns the symbols and diagnostics.
1018 1038
    loanLen: u32,
1019 1039
    /// Reference locals in active lexical scopes.
1020 1040
    locals: [LocalLoan; MAX_LINEAR_BINDINGS],
1021 1041
    /// Number of active local loans.
1022 1042
    localLen: u32,
1043 +
    /// Permission identities controlled by active lexical authority bindings.
1044 +
    authorityPermissions: [?*unsafe types::Region; MAX_LINEAR_BINDINGS],
1045 +
    /// Bindings that provide each lexical permission authority.
1046 +
    authorityBindings: [?*unsafe mut Symbol; MAX_LINEAR_BINDINGS],
1047 +
    /// Whether each lexical authority permits exclusive payload access.
1048 +
    authorityExclusive: [bool; MAX_LINEAR_BINDINGS],
1049 +
    /// Number of initialized authority entries.
1050 +
    authorityLen: u32,
1051 +
    /// Associated payload address currently validated by a region header.
1052 +
    payloadAddress: ?*ast::Node,
1053 +
    /// Matching authority reborrow currently being checked.
1054 +
    witnessPermission: ?*unsafe types::Region,
1023 1055
    /// Binding count at entry to each active loop.
1024 1056
    loopMarks: [u32; MAX_LINEAR_LOOP_DEPTH],
1025 1057
    /// Available bindings at entry to each active loop.
1026 1058
    loopAvailable: [u64; MAX_LINEAR_LOOP_DEPTH],
1027 1059
    /// Available bindings shared by the exits from each active loop.
1081 1113
    parameters: *RegionScope,
1082 1114
    /// Region arguments in parameter order.
1083 1115
    arguments: *unsafe [*unsafe types::Region],
1084 1116
    /// Stable descriptor for the substituted field or variant view.
1085 1117
    view: *unsafe mut NominalType,
1118 +
    /// Resolver-private generation of the most recent compile-time traversal.
1119 +
    traversalGeneration: u32,
1120 +
    /// Resolver-private region roles visited during that traversal.
1121 +
    traversalRoles: u8,
1086 1122
    /// Next application in the resolver cache.
1087 -
    next: ?*unsafe NominalApplication,
1123 +
    next: ?*unsafe mut NominalApplication,
1088 1124
    /// Next application in the same lookup bucket.
1089 -
    bucketNext: ?*unsafe NominalApplication,
1125 +
    bucketNext: ?*unsafe mut NominalApplication,
1090 1126
}
1091 1127
1092 1128
/// Global resolver state.
1093 1129
export record Resolver: 'arena {
1094 1130
    /// Number of symbol identities allocated by this resolver.
1095 1131
    symbolCount: u32,
1096 1132
    /// Active region names for source type checking.
1097 1133
    regionScope: ?*RegionScope,
1098 1134
    /// Interned applications of nominal region parameters.
1099 -
    applications: ?*unsafe NominalApplication,
1135 +
    applications: ?*unsafe mut NominalApplication,
1100 1136
    /// First entry in the fully resolved suffix of the application list.
1101 -
    completedApplications: ?*unsafe NominalApplication,
1137 +
    completedApplications: ?*unsafe mut NominalApplication,
1102 1138
    /// Exact application lookup chains, backed by the resolver arena.
1103 -
    applicationBuckets: *unsafe mut [?*unsafe NominalApplication],
1139 +
    applicationBuckets: *unsafe mut [?*unsafe mut NominalApplication],
1140 +
    /// Monotonic identity for cycle-safe compile-time type traversals.
1141 +
    nominalTraversalGeneration: u32,
1104 1142
    /// Cell payload checks that require complete nominal layouts.
1105 1143
    cellChecks: *mut [CellCheck],
1106 1144
    /// Current scope.
1107 1145
    scope: *unsafe mut Scope,
1108 1146
    /// Package scope containing package roots and top-level symbols.
1141 1179
    methods: [MethodEntry; MAX_METHODS],
1142 1180
    /// Number of registered standalone methods.
1143 1181
    methodsLen: u32,
1144 1182
}
1145 1183
1146 -
/// Cell signature whose payload needs a complete nominal layout.
1184 +
/// Deferred cell payload validation that requires a complete nominal layout.
1147 1185
record CellCheck: Copy {
1148 1186
    /// Source signature used for diagnostics.
1149 1187
    node: *ast::Node,
1150 1188
    /// Payload whose layout and ownership must be checked.
1151 1189
    payload: Type,
1190 +
    /// Permission association that makes affine payloads eligible.
1191 +
    permission: ?*unsafe types::Region,
1152 1192
    /// Region environment at the source signature.
1153 1193
    regions: ?*RegionScope,
1154 1194
    /// Module that owns the source signature.
1155 1195
    moduleId: u16,
1156 1196
}
1225 1265
        set *region = types::Region { id: node.id, origin: types::RegionOrigin::Parameter, name, parent: nil };
1226 1266
        set entries[index] = region;
1227 1267
        set index += 1;
1228 1268
    }
1229 1269
    let scope = try! alloc::alloc(&mut *self.arena, @sizeOf(RegionScope), @alignOf(RegionScope)) as *mut RegionScope;
1230 -
    set *scope = RegionScope { declarations: RegionDeclarations::Parameters(nodes), entries, parent: nil };
1270 +
    set *scope = RegionScope {
1271 +
        declarations: RegionDeclarations::Parameters(nodes),
1272 +
        entries,
1273 +
        parent: nil,
1274 +
    };
1231 1275
    let frozen: *RegionScope = scope;
1232 1276
    set index = 0;
1233 1277
    for node in nodes {
1234 1278
        let case ast::NodeValue::Region { parent, .. } = node.value else continue;
1235 1279
        if let parentNode = parent {
1264 1308
}
1265 1309
1266 1310
/// Hash active type fields so equal values select the same lookup chain.
1267 1311
unsafe fn typeHash(ty: Type) -> u32 {
1268 1312
    match ty {
1269 -
        case Type::Cell { class, payload } =>
1270 -
            return addressHash(payload as u64) ^ (classHash(class) * CACHE_HASH_PRIME),
1313 +
        case Type::Cell { class, permission, payload } => {
1314 +
            let mut hash = addressHash(payload as u64) ^ (classHash(class) * CACHE_HASH_PRIME);
1315 +
            if let region = permission {
1316 +
                set hash = (hash ^ addressHash(region as u64)) * CACHE_HASH_PRIME;
1317 +
            }
1318 +
            return hash;
1319 +
        }
1271 1320
        case Type::Pointer { class, target, mutable } =>
1272 1321
            return addressHash(target as u64) ^ (classHash(class) * CACHE_HASH_PRIME) ^ (1 if mutable else 0),
1273 1322
        case Type::Slice { class, item, mutable } =>
1274 1323
            return addressHash(item as u64) ^ (classHash(class) * CACHE_HASH_PRIME) ^ (1 if mutable else 0),
1275 1324
        case Type::TraitObject { class, traitInfo, mutable } =>
1336 1385
    set *layout = value;
1337 1386
    return layout;
1338 1387
}
1339 1388
1340 1389
/// Get the exact arguments of an applied nominal descriptor.
1341 -
export fn nominalApplication(info: &NominalType) -> ?*unsafe NominalApplication {
1390 +
export fn nominalApplication(info: &NominalType) -> ?*unsafe mut NominalApplication {
1342 1391
    match *info {
1343 1392
        case NominalType::Application(applied) => return applied,
1344 1393
        case NominalType::Record(body) => return body.application,
1345 1394
        case NominalType::Union(body) => return body.application,
1346 1395
        else => return nil,
1347 1396
    }
1348 1397
}
1349 1398
1399 +
/// Return the private visit bit for one compile-time region role.
1400 +
fn regionTypeRoleBit(role: RegionTypeRole) -> u8 {
1401 +
    match role {
1402 +
        case RegionTypeRole::CellPermission => return 1,
1403 +
        case RegionTypeRole::Reference => return 2,
1404 +
        case RegionTypeRole::Retention => return 4,
1405 +
        case RegionTypeRole::StorageValidation => return 8,
1406 +
        case RegionTypeRole::StoragePresence => return 16,
1407 +
    }
1408 +
}
1409 +
1410 +
/// Start a cycle-safe nominal traversal without allocating per-call scratch.
1411 +
unsafe fn nextNominalTraversalGeneration 'arena (self: &mut Resolver 'arena) -> u32 {
1412 +
    if self.nominalTraversalGeneration == parser::U32_MAX {
1413 +
        let mut cursor = self.applications;
1414 +
        while let applied = cursor {
1415 +
            set applied.traversalGeneration = 0;
1416 +
            set applied.traversalRoles = 0;
1417 +
            set cursor = applied.next;
1418 +
        }
1419 +
        set self.nominalTraversalGeneration = 0;
1420 +
    }
1421 +
    set self.nominalTraversalGeneration += 1;
1422 +
    return self.nominalTraversalGeneration;
1423 +
}
1424 +
1425 +
/// Mark an applied nominal visited once for a role in one traversal generation.
1426 +
unsafe fn visitNominalApplication(
1427 +
    applied: *unsafe mut NominalApplication,
1428 +
    generation: u32,
1429 +
    role: RegionTypeRole,
1430 +
) -> bool {
1431 +
    if applied.traversalGeneration <> generation {
1432 +
        set applied.traversalGeneration = generation;
1433 +
        set applied.traversalRoles = 0;
1434 +
    }
1435 +
    let bit = regionTypeRoleBit(role);
1436 +
    if (applied.traversalRoles & bit) <> 0 {
1437 +
        return false;
1438 +
    }
1439 +
    set applied.traversalRoles |= bit;
1440 +
    return true;
1441 +
}
1442 +
1350 1443
/// Get source region parameters without forcing a recursive type's layout.
1351 1444
unsafe fn nominalParameters 'arena (self: &mut Resolver 'arena, info: *unsafe NominalType) -> ?*RegionScope
1352 1445
    throws (ResolveError)
1353 1446
{
1354 1447
    match *info {
1440 1533
        self.arena, @sizeOf(NominalApplication), @alignOf(NominalApplication)
1441 1534
    ) as *unsafe mut NominalApplication;
1442 1535
    let view = allocNominalType(self, NominalType::Application(entry));
1443 1536
    set *entry = NominalApplication {
1444 1537
        base, parameters: map.parameters, arguments, view,
1538 +
        traversalGeneration: 0, traversalRoles: 0,
1445 1539
        next: self.applications, bucketNext: self.applicationBuckets[bucket],
1446 1540
    };
1447 1541
    set self.applications = entry;
1448 1542
    set self.applicationBuckets[bucket] = entry;
1449 1543
    return view;
1467 1561
    let scope = parameters else panic "applyNominalRegions: empty application";
1468 1562
    let map = regionSubstitution(self, scope);
1469 1563
    for region, i in regions {
1470 1564
        set map.arguments[i] = try resolveRegion(self, region);
1471 1565
    }
1472 -
    try validateRegionArguments(self, &map, site);
1566 +
    try validateRegionArguments(self, &map, nil, nil, site);
1473 1567
    return internNominalApplication(self, base, &map);
1474 1568
}
1475 1569
1476 1570
/// Complete nominal views stored inline within an applied type.
1477 1571
/// Pointer, slice, and cell targets have independent storage layouts.
1486 1580
        },
1487 1581
    }
1488 1582
}
1489 1583
1490 1584
/// Resolve a substituted member view with the source declaration's shared layout.
1491 -
unsafe fn resolveNominalApplication 'arena (self: &mut Resolver 'arena, applied: *unsafe NominalApplication, site: *ast::Node)
1585 +
unsafe fn resolveNominalApplication 'arena (self: &mut Resolver 'arena, applied: *unsafe mut NominalApplication, site: *ast::Node)
1492 1586
    throws (ResolveError)
1493 1587
{
1494 1588
    try ensureNominalResolved(self, applied.base, site);
1495 1589
    let map = regionSubstitution(self, applied.parameters);
1496 1590
    for argument, i in applied.arguments {
1568 1662
    let mut index: u32 = 0;
1569 1663
    while index < self.cellChecks.len {
1570 1664
        let check = self.cellChecks[index];
1571 1665
        set self.regionScope = check.regions;
1572 1666
        set self.currentMod = check.moduleId;
1573 -
        try validateCellPayload(self, check.node, check.payload) catch error {
1667 +
        try validateCellPayload(self, check.node, check.payload, check.permission) catch error {
1574 1668
            set self.regionScope = previousRegions;
1575 1669
            set self.currentMod = previousModule;
1576 1670
            throw error;
1577 1671
        };
1578 1672
        set index += 1;
1631 1725
    storage: ResolverStorage,
1632 1726
    config: Config
1633 1727
) -> Resolver 'arena {
1634 1728
    let case ResolverStorage { nodeData, pkgScope, errors } = storage else panic "expected resolver storage";
1635 1729
    let applicationBuckets = try! alloc::allocRawSlice(
1636 -
        arena, @sizeOf(?*unsafe NominalApplication), @alignOf(?*unsafe NominalApplication), APPLICATION_BUCKETS
1637 -
    ) as *unsafe mut [?*unsafe NominalApplication];
1730 +
        arena, @sizeOf(?*unsafe mut NominalApplication), @alignOf(?*unsafe mut NominalApplication), APPLICATION_BUCKETS
1731 +
    ) as *unsafe mut [?*unsafe mut NominalApplication];
1638 1732
    for i in 0..applicationBuckets.len {
1639 1733
        set applicationBuckets[i] = nil;
1640 1734
    }
1641 1735
    let types = try! alloc::allocRawSlice(
1642 1736
        arena, @sizeOf(?*TypeNode), @alignOf(?*TypeNode), TYPE_BUCKETS
1681 1775
        symbolCount: 0,
1682 1776
        regionScope: nil,
1683 1777
        applications: nil,
1684 1778
        completedApplications: nil,
1685 1779
        applicationBuckets,
1780 +
        nominalTraversalGeneration: 0,
1686 1781
        cellChecks: &mut [],
1687 1782
        scope: pkgScope,
1688 1783
        pkgScope: pkgScope,
1689 1784
        loopStack: [LoopCtx { hasBreak: false }; MAX_LOOP_DEPTH],
1690 1785
        loopDepth: 0,
2587 2682
        return Coercion::Identity;
2588 2683
    }
2589 2684
    if to == from {
2590 2685
        return Coercion::Identity;
2591 2686
    }
2592 -
    if let case Type::Cell { class, payload } = to {
2593 -
        let case Type::Cell { class: sourceClass, payload: sourcePayload } = from else return nil;
2594 -
        if pointerClassesAssignable(class, sourceClass, self.inUnsafeContext) and typesEqual(*payload, *sourcePayload) {
2687 +
    if let case Type::Cell { class, permission, payload } = to {
2688 +
        let case Type::Cell {
2689 +
            class: sourceClass, permission: sourcePermission, payload: sourcePayload,
2690 +
        } = from else return nil;
2691 +
        let mut storageAssignable = pointerClassesAssignable(
2692 +
            class, sourceClass, self.inUnsafeContext
2693 +
        );
2694 +
        if let case types::PointerClass::Region(targetRegion) = class {
2695 +
            if let case types::PointerClass::Region(sourceRegion) = sourceClass {
2696 +
                set storageAssignable = types::regionContains(sourceRegion, targetRegion);
2697 +
            }
2698 +
        }
2699 +
        if permission == sourcePermission and storageAssignable
2700 +
            and typesEqual(*payload, *sourcePayload)
2701 +
        {
2595 2702
            return Coercion::Identity;
2596 2703
        }
2597 2704
        return nil;
2598 2705
    }
2599 2706
    if let case Type::Pointer { class: lhsClass, target: lhsTarget, mutable: lhsMutable } = to {
2803 2910
            else return false;
2804 2911
        return aClass == bClass and aMutable == bMutable
2805 2912
            and typesEqual(*aItem, *bItem);
2806 2913
    }
2807 2914
    match a {
2808 -
        case Type::Cell { class, payload } => {
2809 -
            let case Type::Cell { class: otherClass, payload: other } = b else return false;
2810 -
            return class == otherClass and typesEqual(*payload, *other);
2915 +
        case Type::Cell { class, permission, payload } => {
2916 +
            let case Type::Cell {
2917 +
                class: otherClass, permission: otherPermission, payload: other,
2918 +
            } = b else return false;
2919 +
            return class == otherClass and permission == otherPermission
2920 +
                and typesEqual(*payload, *other);
2811 2921
        }
2812 2922
        case Type::Array(aa) => {
2813 2923
            let case Type::Array(ab) = b else return false;
2814 2924
            return aa.length == ab.length and typesEqual(*aa.item, *ab.item);
2815 2925
        }
2830 2940
export unsafe fn erasedTypesEqual(a: Type, b: Type) -> bool {
2831 2941
    if typesEqual(a, b) {
2832 2942
        return true;
2833 2943
    }
2834 2944
    match a {
2835 -
        case Type::Cell { class, payload } => {
2836 -
            let case Type::Cell { class: otherClass, payload: other } = b else return false;
2945 +
        case Type::Cell { class, permission, payload } => {
2946 +
            let case Type::Cell {
2947 +
                class: otherClass, permission: otherPermission, payload: other,
2948 +
            } = b else return false;
2949 +
            if (permission == nil) <> (otherPermission == nil) {
2950 +
                return false;
2951 +
            }
2837 2952
            return erasedClassesEqual(class, otherClass) and erasedTypesEqual(*payload, *other);
2838 2953
        }
2839 2954
        case Type::Session(_) => {
2840 2955
            let case Type::Session(_) = b else return false;
2841 2956
            return true;
2965 3080
        try validateRegionStorage(self, value, ty, region);
2966 3081
    }
2967 3082
}
2968 3083
2969 3084
/// Require all type dependencies to cover the destination or active lexical scope.
3085 +
/// Permission identities are visibility dependencies rather than storage lifetimes.
2970 3086
unsafe fn validateRegionStorage 'arena (
2971 3087
    self: &mut Resolver 'arena, node: *ast::Node, ty: Type, destination: ?*unsafe types::Region
2972 3088
)
2973 3089
    throws (ResolveError)
3090 +
{
3091 +
    let generation = nextNominalTraversalGeneration(self);
3092 +
    try validateRegionStorageType(self, node, ty, destination, generation);
3093 +
}
3094 +
3095 +
/// Walk one value type once per applied nominal descriptor.
3096 +
unsafe fn validateRegionStorageType 'arena (
3097 +
    self: &mut Resolver 'arena,
3098 +
    node: *ast::Node,
3099 +
    ty: Type,
3100 +
    destination: ?*unsafe types::Region,
3101 +
    generation: u32,
3102 +
)
3103 +
    throws (ResolveError)
2974 3104
{
2975 3105
    if let case Type::Session(region) = ty {
2976 3106
        if not regionCoversStorage(self.regionScope, region, destination) {
2977 3107
            throw emitError(self, node, ErrorKind::RegionEscape(region.name));
2978 3108
        }
2981 3111
        if not regionCoversStorage(self.regionScope, region, destination) {
2982 3112
            throw emitError(self, node, ErrorKind::RegionEscape(region.name));
2983 3113
        }
2984 3114
    }
2985 3115
    match ty {
2986 -
        case Type::Pointer { target, .. } => try validateRegionStorage(self, node, *target, destination),
2987 -
        case Type::Slice { item, .. } => try validateRegionStorage(self, node, *item, destination),
2988 -
        case Type::Cell { payload, .. } => try validateRegionStorage(self, node, *payload, destination),
2989 -
        case Type::Array(array) => try validateRegionStorage(self, node, *array.item, destination),
2990 -
        case Type::Optional(inner) => try validateRegionStorage(self, node, *inner, destination),
3116 +
        case Type::Pointer { target, .. } =>
3117 +
            try validateRegionStorageType(
3118 +
                self, node, *target, destination, generation,
3119 +
            ),
3120 +
        case Type::Slice { item, .. } =>
3121 +
            try validateRegionStorageType(
3122 +
                self, node, *item, destination, generation,
3123 +
            ),
3124 +
        case Type::Cell { permission, payload, .. } => {
3125 +
            if let region = permission; not regionInScope(self.regionScope, region.id) {
3126 +
                throw emitError(self, node, ErrorKind::RegionEscape(region.name));
3127 +
            }
3128 +
            try validateRegionStorageType(
3129 +
                self, node, *payload, destination, generation,
3130 +
            );
3131 +
        }
3132 +
        case Type::Array(array) =>
3133 +
            try validateRegionStorageType(
3134 +
                self, node, *array.item, destination, generation,
3135 +
            ),
3136 +
        case Type::Optional(inner) =>
3137 +
            try validateRegionStorageType(
3138 +
                self, node, *inner, destination, generation,
3139 +
            ),
2991 3140
        case Type::Nominal(info) => {
2992 -
            if let applied = nominalApplication(info) {
2993 -
                for region in applied.arguments {
2994 -
                    if not regionCoversStorage(self.regionScope, region, destination) {
2995 -
                        throw emitError(self, node, ErrorKind::RegionEscape(region.name));
3141 +
            let applied = nominalApplication(info) else return;
3142 +
            for region in applied.arguments {
3143 +
                if not regionInScope(self.regionScope, region.id) {
3144 +
                    throw emitError(self, node, ErrorKind::RegionEscape(region.name));
3145 +
                }
3146 +
            }
3147 +
            if not visitNominalApplication(
3148 +
                applied, generation, RegionTypeRole::StorageValidation,
3149 +
            ) {
3150 +
                return;
3151 +
            }
3152 +
            match *info {
3153 +
                case NominalType::Record(recordType) => {
3154 +
                    for field in recordType.fields {
3155 +
                        try validateRegionStorageType(
3156 +
                            self, node, field.fieldType, destination, generation,
3157 +
                        );
3158 +
                    }
3159 +
                }
3160 +
                case NominalType::Union(unionType) => {
3161 +
                    for variant in unionType.variants {
3162 +
                        try validateRegionStorageType(
3163 +
                            self, node, variant.valueType, destination, generation,
3164 +
                        );
2996 3165
                    }
2997 3166
                }
3167 +
                // Unresolved applications have no member view to inspect yet.
3168 +
                case NominalType::Placeholder(_), NominalType::Resolving(_),
3169 +
                     NominalType::Application(_) => return,
2998 3170
            }
2999 3171
        }
3000 3172
        case Type::Fn(info) => {
3001 3173
            if info.regions <> nil {
3002 3174
                return;
3003 3175
            }
3004 3176
            for parameter in info.paramTypes {
3005 -
                try validateRegionStorage(self, node, *parameter, destination);
3177 +
                try validateRegionStorageType(
3178 +
                    self, node, *parameter, destination, generation,
3179 +
                );
3006 3180
            }
3007 3181
            for error in info.throwList {
3008 -
                try validateRegionStorage(self, node, *error, destination);
3182 +
                try validateRegionStorageType(
3183 +
                    self, node, *error, destination, generation,
3184 +
                );
3009 3185
            }
3010 -
            try validateRegionStorage(self, node, *info.returnType, destination);
3186 +
            try validateRegionStorageType(
3187 +
                self, node, *info.returnType, destination, generation,
3188 +
            );
3011 3189
        }
3012 -
        else => {
3013 -
        },
3190 +
        else => {}
3191 +
    }
3192 +
}
3193 +
3194 +
/// Return whether a value type carries a named storage lifetime.
3195 +
/// Cell permission identities authorize access and do not constrain storage.
3196 +
unsafe fn containsStorageRegion 'arena (
3197 +
    self: &mut Resolver 'arena, node: *ast::Node, root: Type
3198 +
) -> bool throws (ResolveError) {
3199 +
    let generation = nextNominalTraversalGeneration(self);
3200 +
    return try typeContainsStorageRegion(self, node, root, generation);
3201 +
}
3202 +
3203 +
/// Search one value type once per applied nominal descriptor.
3204 +
unsafe fn typeContainsStorageRegion 'arena (
3205 +
    self: &mut Resolver 'arena, node: *ast::Node, ty: Type, generation: u32
3206 +
) -> bool throws (ResolveError) {
3207 +
    match ty {
3208 +
        case Type::Cell { class, payload, .. } => {
3209 +
            if let case types::PointerClass::Region(_) = class {
3210 +
                return true;
3211 +
            }
3212 +
            return try typeContainsStorageRegion(self, node, *payload, generation);
3213 +
        }
3214 +
        case Type::Session(_) => return true,
3215 +
        case Type::Pointer { class, target, .. } => {
3216 +
            if let case types::PointerClass::Region(_) = class {
3217 +
                return true;
3218 +
            }
3219 +
            return try typeContainsStorageRegion(self, node, *target, generation);
3220 +
        }
3221 +
        case Type::Slice { class, item, .. } => {
3222 +
            if let case types::PointerClass::Region(_) = class {
3223 +
                return true;
3224 +
            }
3225 +
            return try typeContainsStorageRegion(self, node, *item, generation);
3226 +
        }
3227 +
        case Type::TraitObject { class, .. } => {
3228 +
            if let case types::PointerClass::Region(_) = class {
3229 +
                return true;
3230 +
            }
3231 +
            return false;
3232 +
        }
3233 +
        case Type::Array(array) =>
3234 +
            return try typeContainsStorageRegion(self, node, *array.item, generation),
3235 +
        case Type::Optional(inner) =>
3236 +
            return try typeContainsStorageRegion(self, node, *inner, generation),
3237 +
        case Type::Range { start, end } => {
3238 +
            if let startType = start;
3239 +
                try typeContainsStorageRegion(self, node, *startType, generation)
3240 +
            {
3241 +
                return true;
3242 +
            }
3243 +
            if let endType = end {
3244 +
                return try typeContainsStorageRegion(self, node, *endType, generation);
3245 +
            }
3246 +
            return false;
3247 +
        }
3248 +
        case Type::Nominal(info) => {
3249 +
            try ensureNominalResolved(self, info, node);
3250 +
            let applied = nominalApplication(info) else return false;
3251 +
            if not visitNominalApplication(
3252 +
                applied, generation, RegionTypeRole::StoragePresence,
3253 +
            ) {
3254 +
                return false;
3255 +
            }
3256 +
            match *info {
3257 +
                case NominalType::Record(recordType) => {
3258 +
                    for field in recordType.fields {
3259 +
                        if try typeContainsStorageRegion(
3260 +
                            self, node, field.fieldType, generation,
3261 +
                        ) {
3262 +
                            return true;
3263 +
                        }
3264 +
                    }
3265 +
                }
3266 +
                case NominalType::Union(unionType) => {
3267 +
                    for variant in unionType.variants {
3268 +
                        if try typeContainsStorageRegion(
3269 +
                            self, node, variant.valueType, generation,
3270 +
                        ) {
3271 +
                            return true;
3272 +
                        }
3273 +
                    }
3274 +
                }
3275 +
                case NominalType::Placeholder(_), NominalType::Resolving(_),
3276 +
                     NominalType::Application(_) =>
3277 +
                    panic "typeContainsStorageRegion: unresolved nominal type",
3278 +
            }
3279 +
            return false;
3280 +
        }
3281 +
        case Type::Fn(info) => {
3282 +
            if info.regions <> nil {
3283 +
                return false;
3284 +
            }
3285 +
            for parameter in info.paramTypes {
3286 +
                if try typeContainsStorageRegion(
3287 +
                    self, node, *parameter, generation,
3288 +
                ) {
3289 +
                    return true;
3290 +
                }
3291 +
            }
3292 +
            for error in info.throwList {
3293 +
                if try typeContainsStorageRegion(self, node, *error, generation) {
3294 +
                    return true;
3295 +
                }
3296 +
            }
3297 +
            return try typeContainsStorageRegion(
3298 +
                self, node, *info.returnType, generation,
3299 +
            );
3300 +
        }
3301 +
        else => return false,
3014 3302
    }
3015 3303
}
3016 3304
3017 3305
/// Return whether a type has an explicit region dependency.
3018 3306
unsafe fn containsRegion(ty: Type) -> bool {
3019 3307
    match ty {
3020 -
        case Type::Cell { class, payload } => {
3308 +
        case Type::Cell { class, permission, payload } => {
3309 +
            if permission <> nil {
3310 +
                return true;
3311 +
            }
3021 3312
            if let case types::PointerClass::Region(_) = class {
3022 3313
                return true;
3023 3314
            }
3024 3315
            return containsRegion(*payload);
3025 3316
        }
4191 4482
    let entries = try! alloc::allocRawSlice(
4192 4483
        self.arena, @sizeOf(*unsafe mut types::Region), @alignOf(*unsafe mut types::Region), 1
4193 4484
    ) as *unsafe mut [*unsafe mut types::Region];
4194 4485
    set entries[0] = region;
4195 4486
    let scope = try! alloc::alloc(&mut *self.arena, @sizeOf(RegionScope), @alignOf(RegionScope)) as *mut RegionScope;
4196 -
    set *scope = RegionScope { declarations: RegionDeclarations::Block(node), entries, parent: self.regionScope };
4487 +
    set *scope = RegionScope {
4488 +
        declarations: RegionDeclarations::Block(node),
4489 +
        entries,
4490 +
        parent: self.regionScope,
4491 +
    };
4197 4492
    return scope;
4198 4493
}
4199 4494
4200 4495
/// Qualify an existing-place borrow with its block's region.
4496 +
///
4497 +
/// A permission cell loan deliberately joins independent storage and
4498 +
/// permission regions. Its paired authority witness proves the lexical
4499 +
/// shortening that the single-parent region graph cannot represent.
4201 4500
unsafe fn qualifyBlockBorrow 'arena (
4202 -
    self: &mut Resolver 'arena, node: *ast::Node, ty: Type, region: *unsafe types::Region
4501 +
    self: &mut Resolver 'arena, node: *ast::Node, ty: Type,
4502 +
    region: *unsafe types::Region, hasPermissionWitness: bool
4203 4503
) -> Type throws (ResolveError) {
4204 4504
    let mut class = types::PointerClass::Ref;
4205 4505
    match ty {
4206 4506
        case Type::Cell { class: cellClass, .. } => set class = cellClass,
4207 4507
        case Type::Pointer { class: pointerClass, .. } => set class = pointerClass,
4208 4508
        case Type::Slice { class: sliceClass, .. } => set class = sliceClass,
4209 4509
        else => throw emitError(self, node, ErrorKind::RefBinding),
4210 4510
    }
4211 4511
    if let case types::PointerClass::Region(source) = class {
4212 -
        if not types::regionContains(source, region) {
4512 +
        if not hasPermissionWitness and not types::regionContains(source, region) {
4213 4513
            throw emitError(self, node, ErrorKind::RegionParent(region.name));
4214 4514
        }
4215 4515
    }
4216 4516
    match ty {
4217 -
        case Type::Cell { payload, .. } =>
4218 -
            return Type::Cell { class: types::PointerClass::Region(region), payload },
4517 +
        case Type::Cell { permission, payload, .. } =>
4518 +
            return Type::Cell {
4519 +
                class: types::PointerClass::Region(region), permission, payload,
4520 +
            },
4219 4521
        case Type::Pointer { target, mutable, .. } =>
4220 4522
            return Type::Pointer { class: types::PointerClass::Region(region), target, mutable },
4221 4523
        case Type::Slice { item, mutable, .. } =>
4222 4524
            return Type::Slice { class: types::PointerClass::Region(region), item, mutable },
4223 4525
        else => throw emitError(self, node, ErrorKind::RefBinding),
4232 4534
    if self.currentFn == nil {
4233 4535
        throw emitError(self, node, ErrorKind::InvalidRefPosition);
4234 4536
    }
4235 4537
    let scope = try borrowRegion(self, regionNode);
4236 4538
    let region = scope.entries[0];
4539 +
    let mut authorityPermissions: [?*unsafe types::Region; MAX_REGIONAL_LOANS] =
4540 +
        [nil; MAX_REGIONAL_LOANS];
4541 +
    let mut authorityExclusive: [bool; MAX_REGIONAL_LOANS] =
4542 +
        [false; MAX_REGIONAL_LOANS];
4543 +
    let mut authorityLen: u32 = 0;
4544 +
    let mut payloadPermissions: [?*unsafe types::Region; MAX_REGIONAL_LOANS] =
4545 +
        [nil; MAX_REGIONAL_LOANS];
4546 +
    let mut payloadExclusive: [bool; MAX_REGIONAL_LOANS] =
4547 +
        [false; MAX_REGIONAL_LOANS];
4548 +
    let mut payloadLen: u32 = 0;
4237 4549
    for bindingNode in bindings {
4238 4550
        let case ast::NodeValue::RegionBinding(binding) = bindingNode.value
4239 4551
            else panic "resolveBorrowBlock: invalid binding node";
4240 4552
        let case ast::NodeValue::AddressOf(address) = binding.value.value
4241 4553
            else panic "resolveBorrowBlock: invalid source node";
4242 -
        let ty = try infer(self, binding.value);
4554 +
        try infer(self, binding.value);
4243 4555
        if not ast::isPlaceExpr(address.target) or borrowPlace(self, address.target).root == nil {
4244 4556
            throw emitError(self, binding.value, ErrorKind::RefBinding);
4245 4557
        }
4246 -
        let qualified = try qualifyBlockBorrow(self, binding.value, ty, region);
4558 +
        if address.kind == ast::AddressKind::Cell {
4559 +
            continue;
4560 +
        }
4561 +
        if let cellTy = try inferCellPayload(self, address.target) {
4562 +
            if let case Type::Cell { permission: controlled, .. } = cellTy {
4563 +
                if let permission = controlled {
4564 +
                    if payloadLen >= MAX_REGIONAL_LOANS {
4565 +
                        throw emitError(self, binding.value, ErrorKind::RegionalLoanOverflow);
4566 +
                    }
4567 +
                    set payloadPermissions[payloadLen] = permission;
4568 +
                    set payloadExclusive[payloadLen] =
4569 +
                        address.kind == ast::AddressKind::Mutable;
4570 +
                    set payloadLen += 1;
4571 +
                    continue;
4572 +
                }
4573 +
            }
4574 +
        }
4575 +
        if let case ast::NodeValue::Deref(source) = address.target.value {
4576 +
            let sourceTy = try infer(self, source);
4577 +
            if let case Type::Pointer {
4578 +
                class: types::PointerClass::Region(permission),
4579 +
                mutable: true,
4580 +
                ..
4581 +
            } = sourceTy {
4582 +
                if authorityLen >= MAX_REGIONAL_LOANS {
4583 +
                    throw emitError(self, binding.value, ErrorKind::RegionalLoanOverflow);
4584 +
                }
4585 +
                set authorityPermissions[authorityLen] = permission;
4586 +
                set authorityExclusive[authorityLen] =
4587 +
                    address.kind == ast::AddressKind::Mutable;
4588 +
                set authorityLen += 1;
4589 +
            }
4590 +
        }
4591 +
    }
4592 +
    for bindingNode in bindings {
4593 +
        let case ast::NodeValue::RegionBinding(binding) = bindingNode.value
4594 +
            else panic "resolveBorrowBlock: invalid binding node";
4595 +
        let case ast::NodeValue::AddressOf(address) = binding.value.value
4596 +
            else panic "resolveBorrowBlock: invalid source node";
4597 +
        let mut permission: ?*unsafe types::Region = nil;
4598 +
        let mut isPayload = false;
4599 +
        if address.kind <> ast::AddressKind::Cell {
4600 +
            if let cellTy = try inferCellPayload(self, address.target) {
4601 +
                if let case Type::Cell { permission: controlled, .. } = cellTy {
4602 +
                    set permission = controlled;
4603 +
                    set isPayload = controlled <> nil;
4604 +
                }
4605 +
            }
4606 +
            if permission == nil {
4607 +
                if let case ast::NodeValue::Deref(source) = address.target.value {
4608 +
                    let sourceTy = try infer(self, source);
4609 +
                    if let case Type::Pointer {
4610 +
                        class: types::PointerClass::Region(controlled),
4611 +
                        mutable: true,
4612 +
                        ..
4613 +
                    } = sourceTy {
4614 +
                        set permission = controlled;
4615 +
                    }
4616 +
                }
4617 +
            }
4618 +
        }
4619 +
        let mut hasPermissionWitness = false;
4620 +
        if let controlled = permission {
4621 +
            let exclusive = address.kind == ast::AddressKind::Mutable;
4622 +
            if isPayload {
4623 +
                for i in 0..authorityLen {
4624 +
                    let candidate = authorityPermissions[i]
4625 +
                        else panic "resolveBorrowBlock: missing authority permission";
4626 +
                    if candidate.id == controlled.id and authorityExclusive[i] == exclusive {
4627 +
                        set hasPermissionWitness = true;
4628 +
                        break;
4629 +
                    }
4630 +
                }
4631 +
            } else {
4632 +
                for i in 0..payloadLen {
4633 +
                    let candidate = payloadPermissions[i]
4634 +
                        else panic "resolveBorrowBlock: missing payload permission";
4635 +
                    if candidate.id == controlled.id and payloadExclusive[i] == exclusive {
4636 +
                        set hasPermissionWitness = true;
4637 +
                        break;
4638 +
                    }
4639 +
                }
4640 +
            }
4641 +
        }
4642 +
        let ty = try infer(self, binding.value);
4643 +
        let qualified = try qualifyBlockBorrow(
4644 +
            self, binding.value, ty, region, hasPermissionWitness,
4645 +
        );
4247 4646
        setNodeType(self, binding.value, qualified);
4248 4647
    }
4249 4648
    let previous = self.regionScope;
4250 4649
    set self.regionScope = scope;
4251 4650
    set self.nodeData.entries[node.id].extra = NodeExtra::Regions(scope);
4339 4738
    let scope = try borrowRegion(self, regionNode);
4340 4739
    let region = scope.entries[0];
4341 4740
    if let sourceRegion = referenceRegion(ty) {
4342 4741
        set region.parent = sourceRegion;
4343 4742
    }
4344 -
    setNodeType(self, binding.value, try qualifyBlockBorrow(self, binding.value, ty, region));
4743 +
    setNodeType(self, binding.value, try qualifyBlockBorrow(self, binding.value, ty, region, false));
4345 4744
    let previous = self.regionScope;
4346 4745
    set self.regionScope = scope;
4347 4746
    set self.nodeData.entries[node.id].extra = NodeExtra::Regions(scope);
4348 4747
    enterScope(self, node);
4349 4748
    let result = try resolveSessionBody(self, bindingNode, binding, region, body) catch error {
5260 5659
    }
5261 5660
    let map = regionSubstitution(self, sourceScope);
5262 5661
    for _, i in sourceScope.entries {
5263 5662
        set map.arguments[i] = targetScope.entries[offset + i];
5264 5663
    }
5265 -
    try validateRegionArguments(self, &map, site);
5664 +
    try validateRegionArguments(self, &map, nil, nil, site);
5266 5665
    return map;
5267 5666
}
5268 5667
5269 5668
/// Resolved implementation of one trait method.
5270 5669
record ResolvedInstanceMethod: Copy {
7052 7451
/// Infer regions through matching type structure without adding lifetime subtyping.
7053 7452
unsafe fn inferRegionArguments 'arena (
7054 7453
    self: &mut Resolver 'arena, map: &RegionSubstitution, expected: Type, actual: Type, site: *ast::Node
7055 7454
) throws (ResolveError) {
7056 7455
    match expected {
7057 -
        case Type::Cell { class, payload } => {
7058 -
            let case Type::Cell { class: otherClass, payload: other } = actual else return;
7456 +
        case Type::Cell { class, permission, payload } => {
7457 +
            let case Type::Cell {
7458 +
                class: otherClass, permission: otherPermission, payload: other,
7459 +
            } = actual else return;
7059 7460
            try inferRegionClass(self, map, class, otherClass, site);
7461 +
            if let expectedPermission = permission {
7462 +
                let actualPermission = otherPermission else return;
7463 +
                try inferRegionClass(
7464 +
                    self, map,
7465 +
                    types::PointerClass::Region(expectedPermission),
7466 +
                    types::PointerClass::Region(actualPermission),
7467 +
                    site
7468 +
                );
7469 +
            }
7060 7470
            try inferRegionArguments(self, map, *payload, *other, site);
7061 7471
        }
7062 7472
        case Type::Session(region) => {
7063 7473
            let case Type::Session(other) = actual else return;
7064 7474
            try inferRegionClass(self, map, types::PointerClass::Region(region),
7119 7529
        else => {
7120 7530
        }
7121 7531
    }
7122 7532
}
7123 7533
7124 -
/// Require a total substitution whose arguments satisfy each parent relation.
7125 -
unsafe fn validateRegionArguments 'arena (self: &mut Resolver 'arena, map: &RegionSubstitution, site: *ast::Node)
7126 -
    throws (ResolveError)
7127 -
{
7534 +
/// Return whether a type uses one formal region as a cell permission.
7535 +
/// Unapplied nominals cannot capture a free formal region, so only exact
7536 +
/// applications need cycle marking and member traversal.
7537 +
unsafe fn typeHasFormalCellPermission 'arena (
7538 +
    self: &mut Resolver 'arena,
7539 +
    ty: Type,
7540 +
    permission: *unsafe types::Region,
7541 +
    generation: u32,
7542 +
    site: *ast::Node,
7543 +
) -> bool throws (ResolveError) {
7544 +
    match ty {
7545 +
        case Type::Cell { permission: identity, payload, .. } => {
7546 +
            if let cellPermission = identity; cellPermission == permission {
7547 +
                return true;
7548 +
            }
7549 +
            return try typeHasFormalCellPermission(
7550 +
                self, *payload, permission, generation, site,
7551 +
            );
7552 +
        }
7553 +
        case Type::Pointer { target, .. } =>
7554 +
            return try typeHasFormalCellPermission(
7555 +
                self, *target, permission, generation, site,
7556 +
            ),
7557 +
        case Type::Slice { item, .. } =>
7558 +
            return try typeHasFormalCellPermission(
7559 +
                self, *item, permission, generation, site,
7560 +
            ),
7561 +
        case Type::Array(array) =>
7562 +
            return try typeHasFormalCellPermission(
7563 +
                self, *array.item, permission, generation, site,
7564 +
            ),
7565 +
        case Type::Optional(inner) =>
7566 +
            return try typeHasFormalCellPermission(
7567 +
                self, *inner, permission, generation, site,
7568 +
            ),
7569 +
        case Type::Range { start, end } => {
7570 +
            if let startType = start;
7571 +
                try typeHasFormalCellPermission(
7572 +
                    self, *startType, permission, generation, site,
7573 +
                )
7574 +
            {
7575 +
                return true;
7576 +
            }
7577 +
            if let endType = end {
7578 +
                return try typeHasFormalCellPermission(
7579 +
                    self, *endType, permission, generation, site,
7580 +
                );
7581 +
            }
7582 +
            return false;
7583 +
        }
7584 +
        case Type::Nominal(nominal) => {
7585 +
            let applied = nominalApplication(nominal) else return false;
7586 +
            try ensureNominalResolved(self, nominal, site);
7587 +
            if not visitNominalApplication(
7588 +
                applied, generation, RegionTypeRole::CellPermission,
7589 +
            ) {
7590 +
                return false;
7591 +
            }
7592 +
            match *nominal {
7593 +
                case NominalType::Record(recordType) => {
7594 +
                    for field in recordType.fields {
7595 +
                        if try typeHasFormalCellPermission(
7596 +
                            self, field.fieldType, permission, generation, site,
7597 +
                        ) {
7598 +
                            return true;
7599 +
                        }
7600 +
                    }
7601 +
                }
7602 +
                case NominalType::Union(unionType) => {
7603 +
                    for variant in unionType.variants {
7604 +
                        if try typeHasFormalCellPermission(
7605 +
                            self, variant.valueType, permission, generation, site,
7606 +
                        ) {
7607 +
                            return true;
7608 +
                        }
7609 +
                    }
7610 +
                }
7611 +
                case NominalType::Placeholder(_), NominalType::Resolving(_),
7612 +
                     NominalType::Application(_) =>
7613 +
                    panic "typeHasFormalCellPermission: unresolved application",
7614 +
            }
7615 +
            return false;
7616 +
        }
7617 +
        case Type::Fn(info) => {
7618 +
            for parameter in info.paramTypes {
7619 +
                if try typeHasFormalCellPermission(
7620 +
                    self, *parameter, permission, generation, site,
7621 +
                ) {
7622 +
                    return true;
7623 +
                }
7624 +
            }
7625 +
            for error in info.throwList {
7626 +
                if try typeHasFormalCellPermission(
7627 +
                    self, *error, permission, generation, site,
7628 +
                ) {
7629 +
                    return true;
7630 +
                }
7631 +
            }
7632 +
            return try typeHasFormalCellPermission(
7633 +
                self, *info.returnType, permission, generation, site,
7634 +
            );
7635 +
        }
7636 +
        else => return false,
7637 +
    }
7638 +
}
7639 +
7640 +
/// Return whether a function contract uses one formal cell permission.
7641 +
unsafe fn contractHasFormalCellPermission 'arena (
7642 +
    self: &mut Resolver 'arena,
7643 +
    info: *FnType,
7644 +
    receiver: ?Type,
7645 +
    permission: *unsafe types::Region,
7646 +
    generation: u32,
7647 +
    site: *ast::Node,
7648 +
) -> bool throws (ResolveError) {
7649 +
    if let receiverType = receiver;
7650 +
        try typeHasFormalCellPermission(
7651 +
            self, receiverType, permission, generation, site,
7652 +
        )
7653 +
    {
7654 +
        return true;
7655 +
    }
7656 +
    for parameter in info.paramTypes {
7657 +
        if try typeHasFormalCellPermission(
7658 +
            self, *parameter, permission, generation, site,
7659 +
        ) {
7660 +
            return true;
7661 +
        }
7662 +
    }
7663 +
    if try typeHasFormalCellPermission(
7664 +
        self, *info.returnType, permission, generation, site,
7665 +
    ) {
7666 +
        return true;
7667 +
    }
7668 +
    for error in info.throwList {
7669 +
        if try typeHasFormalCellPermission(
7670 +
            self, *error, permission, generation, site,
7671 +
        ) {
7672 +
            return true;
7673 +
        }
7674 +
    }
7675 +
    return false;
7676 +
}
7677 +
7678 +
/// Validate region parents and keep distinct formal cell permissions injective.
7679 +
unsafe fn validateRegionArguments 'arena (
7680 +
    self: &mut Resolver 'arena,
7681 +
    map: &RegionSubstitution,
7682 +
    contract: ?*FnType,
7683 +
    receiver: ?Type,
7684 +
    site: *ast::Node,
7685 +
) throws (ResolveError) {
7128 7686
    for parameter, i in map.parameters.entries {
7129 7687
        if map.arguments[i] == nil {
7130 7688
            throw emitError(self, site, ErrorKind::RegionInference(parameter.name));
7131 7689
        }
7132 7690
    }
7133 7691
    for parameter, i in map.parameters.entries {
7134 7692
        let parent = parameter.parent else continue;
7135 -
        let index = regionIndex(map.parameters, parent.id) else panic "validateRegionArguments: unknown parent";
7136 -
        let parentArgument = map.arguments[index] else panic "validateRegionArguments: missing parent argument";
7137 -
        let argument = map.arguments[i] else panic "validateRegionArguments: missing argument";
7693 +
        let index = regionIndex(map.parameters, parent.id)
7694 +
            else panic "validateRegionArguments: unknown parent";
7695 +
        let parentArgument = map.arguments[index]
7696 +
            else panic "validateRegionArguments: missing parent argument";
7697 +
        let argument = map.arguments[i]
7698 +
            else panic "validateRegionArguments: missing argument";
7138 7699
        if not types::regionContains(parentArgument, argument) {
7139 7700
            throw emitError(self, site, ErrorKind::RegionParent(parameter.name));
7140 7701
        }
7141 7702
    }
7703 +
    let info = contract else return;
7704 +
7705 +
    // Only colliding arguments need contract scans. Formal parameters bound the
7706 +
    // candidates, while generation marks keep recursive applications finite.
7707 +
    for parameter, i in map.parameters.entries {
7708 +
        let argument = map.arguments[i]
7709 +
            else panic "validateRegionArguments: missing argument";
7710 +
        let mut checked = false;
7711 +
        for j in 0..i {
7712 +
            let previousArgument = map.arguments[j]
7713 +
                else panic "validateRegionArguments: missing previous argument";
7714 +
            if previousArgument <> argument {
7715 +
                continue;
7716 +
            }
7717 +
            if not checked {
7718 +
                let generation = nextNominalTraversalGeneration(self);
7719 +
                set checked = true;
7720 +
                if not try contractHasFormalCellPermission(
7721 +
                    self, info, receiver, parameter, generation, site,
7722 +
                ) {
7723 +
                    break;
7724 +
                }
7725 +
            }
7726 +
            let previous = map.parameters.entries[j];
7727 +
            let generation = nextNominalTraversalGeneration(self);
7728 +
            if try contractHasFormalCellPermission(
7729 +
                self, info, receiver, previous, generation, site,
7730 +
            ) {
7731 +
                throw emitError(
7732 +
                    self, site, ErrorKind::RegionInference(parameter.name),
7733 +
                );
7734 +
            }
7735 +
        }
7736 +
    }
7142 7737
}
7143 7738
7144 7739
/// Substitute a reference's region while preserving its ownership class.
7145 7740
unsafe fn substituteRegionClass(map: &RegionSubstitution, class: types::PointerClass) -> types::PointerClass {
7146 7741
    let case types::PointerClass::Region(region) = class else return class;
7150 7745
}
7151 7746
7152 7747
/// Substitute free region arguments in a type without changing its runtime layout.
7153 7748
unsafe fn substituteRegions 'arena (self: &mut Resolver 'arena, map: &RegionSubstitution, ty: Type) -> Type {
7154 7749
    match ty {
7155 -
        case Type::Cell { class, payload } =>
7156 -
            return Type::Cell { class: substituteRegionClass(map, class), payload: allocType(self, substituteRegions(self, map, *payload)) },
7750 +
        case Type::Cell { class, permission, payload } => {
7751 +
            let mut substitutedPermission = permission;
7752 +
            if let region = permission {
7753 +
                let case types::PointerClass::Region(argument) = substituteRegionClass(
7754 +
                    map, types::PointerClass::Region(region)
7755 +
                ) else panic "substituteRegions: invalid permission class";
7756 +
                set substitutedPermission = argument;
7757 +
            }
7758 +
            return Type::Cell {
7759 +
                class: substituteRegionClass(map, class),
7760 +
                permission: substitutedPermission,
7761 +
                payload: allocType(self, substituteRegions(self, map, *payload)),
7762 +
            };
7763 +
        }
7157 7764
        case Type::Session(region) => {
7158 7765
            let index = regionIndex(map.parameters, region.id) else return ty;
7159 7766
            let argument = map.arguments[index] else panic "substituteRegions: missing session region";
7160 7767
            return Type::Session(argument);
7161 7768
        }
7256 7863
        if containsRegion(expected) {
7257 7864
            let actual = try visit(self, argument, regionInputHint(self, expected));
7258 7865
            try inferRegionArguments(self, &map, expected, actual, argument);
7259 7866
        }
7260 7867
    }
7261 -
    try validateRegionArguments(self, &map, node);
7868 +
    try validateRegionArguments(self, &map, info, nil, node);
7262 7869
    return substituteFnRegions(self, &map, info, nil);
7263 7870
}
7264 7871
7265 7872
/// Infer a method's region arguments from its receiver and call arguments.
7266 7873
unsafe fn instantiateMethodCall 'arena (
7280 7887
        if containsRegion(expected) {
7281 7888
            let actual = try visit(self, argument, regionInputHint(self, expected));
7282 7889
            try inferRegionArguments(self, &map, expected, actual, argument);
7283 7890
        }
7284 7891
    }
7285 -
    try validateRegionArguments(self, &map, node);
7892 +
    try validateRegionArguments(
7893 +
        self, &map, method.fnType, method.concreteType, node,
7894 +
    );
7286 7895
    return substituteFnRegions(self, &map, method.fnType, nil);
7287 7896
}
7288 7897
7289 7898
/// Apply explicit current-scope regions to a function or nominal type.
7290 7899
unsafe fn resolveRegionApply 'arena (
7310 7919
    let scope = info.regions else panic "resolveRegionApply: empty region application";
7311 7920
    let map = regionSubstitution(self, scope);
7312 7921
    for region, i in regions {
7313 7922
        set map.arguments[i] = try resolveRegion(self, region);
7314 7923
    }
7315 -
    try validateRegionArguments(self, &map, node);
7924 +
    try validateRegionArguments(self, &map, info, nil, node);
7316 7925
    let applied = substituteFnRegions(self, &map, info, nil);
7317 7926
    if let symbol = symbolFor(self, value) {
7318 7927
        setNodeSymbol(self, node, symbol);
7319 7928
    }
7320 7929
    return setNodeType(self, node, Type::Fn(applied));
7571 8180
        kind, item, traitInfo, methodIndex: runtime.index,
7572 8181
    });
7573 8182
    return setNodeType(self, node, result);
7574 8183
}
7575 8184
7576 -
/// Require a complete payload that can be copied and discarded by value.
7577 -
unsafe fn validateCellPayload 'arena (self: &mut Resolver 'arena, node: *ast::Node, payload: Type) throws (ResolveError) {
8185 +
/// Require a complete, bulk-discardable cell payload, and Copy when unassociated.
8186 +
unsafe fn validateCellPayload 'arena (
8187 +
    self: &mut Resolver 'arena,
8188 +
    node: *ast::Node,
8189 +
    payload: Type,
8190 +
    permission: ?*unsafe types::Region,
8191 +
) throws (ResolveError) {
7578 8192
    try ensureStorableType(self, node, payload);
7579 8193
    try ensureTypeResolved(self, payload, node);
7580 8194
    if not isTypeInferrable(payload) or payload == Type::Void or payload == Type::Opaque
7581 -
        or not isCopy(payload) or not isBulkDiscardable(payload)
8195 +
        or (permission == nil and not isCopy(payload)) or not isBulkDiscardable(payload)
7582 8196
    {
7583 8197
        throw emitError(self, node, ErrorKind::InvalidCellPayload);
7584 8198
    }
7585 8199
    if not hasAllocationLayout(payload) {
7586 8200
        throw emitError(self, node, ErrorKind::InvalidAllocationLayout);
7664 8278
                }
7665 8279
            }
7666 8280
            let applied = try instantiateCall(self, node, call, method.fnType);
7667 8281
            try resolveInlineTypeViews(self, *applied.returnType, node);
7668 8282
            try checkCallArgs(self, node, call, applied, ctx);
8283 +
            setNodeType(self, call.callee, Type::Fn(applied));
7669 8284
            setTraitMethodCall(self, node, traitInfo, method.index);
7670 8285
7671 8286
            return setNodeType(self, node, *applied.returnType);
7672 8287
        }
7673 8288
7687 8302
                let applied = try instantiateMethodCall(
7688 8303
                    self, node, call, access.parent, subjectTy, method
7689 8304
                );
7690 8305
                try resolveInlineTypeViews(self, *applied.returnType, node);
7691 8306
                try checkCallArgs(self, node, call, applied, ctx);
8307 +
                setNodeType(self, call.callee, Type::Fn(applied));
7692 8308
                set self.nodeData.entries[node.id].extra = NodeExtra::MethodCall { method };
7693 8309
7694 8310
                return setNodeType(self, node, *applied.returnType);
7695 8311
            }
7696 8312
        }
7810 8426
    // Slice assignment: `slice[range] = value`.
7811 8427
    if let case ast::NodeValue::Subscript { container, index } = assign.left.value {
7812 8428
        if let case ast::NodeValue::Range(range) = index.value {
7813 8429
            try infer(self, index);
7814 8430
            let containerTy = try infer(self, container);
7815 -
            if not try canMutateThrough(self, container) {
8431 +
            let cellTy = try inferCellPayload(self, container);
8432 +
            if cellTy == nil and not try canMutateThrough(self, container) {
7816 8433
                throw emitError(self, container, ErrorKind::ImmutableBinding);
7817 8434
            }
7818 8435
            let subjectTy = autoDeref(containerTy);
7819 8436
            try checkSliceRangeIndices(self, range);
7820 8437
7838 8455
                    );
7839 8456
                }
7840 8457
            } else {
7841 8458
                try checkAssignable(self, assign.right, *item);
7842 8459
            }
7843 -
            try validateRegionalStore(self, assign.left, assign.right, *item);
8460 +
            if let controlled = cellTy {
8461 +
                let case Type::Cell { class, .. } = controlled
8462 +
                    else panic "resolveAssign: invalid cell range payload";
8463 +
                if let case types::PointerClass::Region(region) = class {
8464 +
                    try validateRegionStorage(self, assign.right, *item, region);
8465 +
                } else if class == types::PointerClass::Owned
8466 +
                    and try containsStorageRegion(self, assign.right, *item)
8467 +
                {
8468 +
                    throw emitError(self, assign.right, ErrorKind::InvalidCellPayload);
8469 +
                }
8470 +
            } else {
8471 +
                try validateRegionalStore(self, assign.left, assign.right, *item);
8472 +
            }
7844 8473
            setSliceRangeInfo(self, node, info);
7845 8474
            setNodeType(self, assign.left, *item);
7846 8475
7847 8476
            return setNodeType(self, node, Type::Void);
7848 8477
        }
7849 8478
    }
7850 8479
    let leftTy = try infer(self, assign.left);
7851 8480
7852 -
    if let case ast::NodeValue::Deref(target) = assign.left.value {
7853 -
        if let case Type::Cell { class, .. } = try infer(self, target) {
7854 -
            try checkAssignable(self, assign.right, leftTy);
7855 -
            if let case types::PointerClass::Region(region) = class {
7856 -
                try validateRegionStorage(self, assign.right, leftTy, region);
7857 -
            } else if class == types::PointerClass::Owned and containsRegion(leftTy) {
7858 -
                throw emitError(self, assign.right, ErrorKind::InvalidCellPayload);
7859 -
            }
7860 -
            return setNodeType(self, node, leftTy);
8481 +
    if let cellTy = try inferCellPayload(self, assign.left) {
8482 +
        let case Type::Cell { class, .. } = cellTy
8483 +
            else panic "resolveAssign: invalid cell payload";
8484 +
        try checkAssignable(self, assign.right, leftTy);
8485 +
        if let case types::PointerClass::Region(region) = class {
8486 +
            try validateRegionStorage(self, assign.right, leftTy, region);
8487 +
        } else if class == types::PointerClass::Owned
8488 +
            and try containsStorageRegion(self, assign.right, leftTy)
8489 +
        {
8490 +
            throw emitError(self, assign.right, ErrorKind::InvalidCellPayload);
7861 8491
        }
8492 +
        return setNodeType(self, node, leftTy);
7862 8493
    }
7863 8494
7864 8495
    // Check if the left-hand side can be assigned to by checking if it's a mutable location.
7865 8496
    if not try canBorrowMutFrom(self, assign.left) {
7866 8497
        throw emitError(self, assign.left, ErrorKind::ImmutableBinding);
8777 9408
        else => {}
8778 9409
    }
8779 9410
    return addressStorageClass(self, target);
8780 9411
}
8781 9412
8782 -
/// Return whether a place projects into a cell payload snapshot.
8783 -
unsafe fn isCellPayloadPlace 'arena (self: &mut Resolver 'arena, node: *ast::Node) -> bool
9413 +
/// Return the cell type whose payload contains a place during type analysis.
9414 +
unsafe fn inferCellPayload 'arena (self: &mut Resolver 'arena, node: *ast::Node) -> ?Type
8784 9415
    throws (ResolveError)
8785 9416
{
8786 9417
    match node.value {
8787 9418
        case ast::NodeValue::Deref(target) => {
8788 -
            if let case Type::Cell { .. } = try infer(self, target) {
8789 -
                return true;
9419 +
            let ty = try infer(self, target);
9420 +
            if let case Type::Cell { .. } = ty {
9421 +
                return ty;
8790 9422
            }
8791 9423
        }
8792 -
        case ast::NodeValue::FieldAccess(access) => return try isCellPayloadPlace(self, access.parent),
8793 -
        case ast::NodeValue::Subscript { container, .. } => return try isCellPayloadPlace(self, container),
9424 +
        case ast::NodeValue::FieldAccess(access) =>
9425 +
            return try inferCellPayload(self, access.parent),
9426 +
        case ast::NodeValue::Subscript { container, .. } =>
9427 +
            return try inferCellPayload(self, container),
8794 9428
        else => {}
8795 9429
    }
8796 -
    return false;
9430 +
    return nil;
8797 9431
}
8798 9432
8799 9433
/// Return whether a typed expression accesses a whole cell payload.
8800 9434
export fn isCellDeref 'arena (self: &Resolver 'arena, node: *ast::Node) -> bool {
8801 9435
    if let case ast::NodeValue::Deref(target) = node.value {
8841 9475
8842 9476
/// Analyze an address-of expression.
8843 9477
unsafe fn resolveAddressOf 'arena (self: &mut Resolver 'arena, node: *ast::Node, addr: ast::AddressOf, hint: Type) -> Type
8844 9478
    throws (ResolveError)
8845 9479
{
8846 -
    if try isCellPayloadPlace(self, addr.target) {
8847 -
        throw emitError(self, addr.target, ErrorKind::ImmutableBinding);
9480 +
    let payloadCell = try inferCellPayload(self, addr.target);
9481 +
    if let cellTy = payloadCell {
9482 +
        let case Type::Cell { permission, .. } = cellTy
9483 +
            else panic "resolveAddressOf: invalid cell payload";
9484 +
        if permission == nil or addr.kind == ast::AddressKind::Cell {
9485 +
            throw emitError(self, addr.target, ErrorKind::ImmutableBinding);
9486 +
        }
8848 9487
    }
8849 9488
    if addr.kind == ast::AddressKind::Cell and not ast::isPlaceExpr(addr.target) {
8850 9489
        throw emitError(self, addr.target, ErrorKind::RefBinding);
8851 9490
    }
8852 -
    if ast::isExclusiveAddress(addr) {
9491 +
    if payloadCell == nil and ast::isExclusiveAddress(addr) {
8853 9492
        if not try canBorrowMutFrom(self, addr.target) {
8854 9493
            throw emitError(self, addr.target, ErrorKind::ImmutableBinding);
8855 9494
        }
8856 9495
    }
8857 9496
    if let case ast::NodeValue::Subscript { container, index } = addr.target.value {
8901 9540
            }
8902 9541
        }
8903 9542
    }
8904 9543
8905 9544
    if addr.kind == ast::AddressKind::Cell {
8906 -
        try validateCellPayload(self, node, targetTy);
9545 +
        let mut permission: ?*unsafe types::Region = nil;
9546 +
        if let permissionNode = addr.permission {
9547 +
            set permission = try resolveRegion(self, permissionNode);
9548 +
        }
9549 +
        try validateCellPayload(self, node, targetTy, permission);
8907 9550
        if let case types::PointerClass::Region(region) = class {
8908 9551
            try validateRegionStorage(self, addr.target, targetTy, region);
8909 -
        } else if class == types::PointerClass::Owned and containsRegion(targetTy) {
9552 +
        } else if class == types::PointerClass::Owned
9553 +
            and try containsStorageRegion(self, addr.target, targetTy)
9554 +
        {
8910 9555
            throw emitError(self, addr.target, ErrorKind::InvalidCellPayload);
8911 9556
        }
8912 -
        return setNodeType(self, node, Type::Cell { class, payload: allocType(self, targetTy) });
9557 +
        return setNodeType(self, node, Type::Cell {
9558 +
            class, permission, payload: allocType(self, targetTy),
9559 +
        });
8913 9560
    }
8914 9561
    if let case Type::Array(arrayInfo) = targetTy {
8915 9562
        match addr.target.value {
8916 9563
            case ast::NodeValue::ArrayLit(_),
8917 9564
                 ast::NodeValue::ArrayRepeatLit(_) =>
8931 9578
/// Analyze a dereference expression.
8932 9579
unsafe fn resolveDeref 'arena (self: &mut Resolver 'arena, node: *ast::Node, targetNode: *ast::Node, hint: Type) -> Type
8933 9580
    throws (ResolveError)
8934 9581
{
8935 9582
    let operandTy = try visit(self, targetNode, hint);
8936 -
    if let case Type::Cell { class, payload } = operandTy {
9583 +
    if let case Type::Cell { class, permission, payload } = operandTy {
8937 9584
        if class == types::PointerClass::Unsafe {
8938 9585
            try requireUnsafe(self, targetNode);
8939 9586
        }
8940 -
        try validateCellPayload(self, node, *payload);
9587 +
        try validateCellPayload(self, node, *payload, permission);
8941 9588
        return setNodeType(self, node, *payload);
8942 9589
    }
8943 9590
    if let case Type::Pointer { class, target, .. } = operandTy {
8944 9591
        if class == types::PointerClass::Unsafe {
8945 9592
            try requireUnsafe(self, targetNode);
9071 9718
    }
9072 9719
9073 9720
    assert sourceTy <> Type::Unknown;
9074 9721
    assert targetTy <> Type::Unknown;
9075 9722
9076 -
    if let case Type::Cell { class, payload } = targetTy {
9723 +
    if let case Type::Cell { class, permission, payload } = targetTy {
9077 9724
        if let case Type::Pointer { class: sourceClass, target, mutable: true } = sourceTy;
9078 -
            sourceClass == class and class <> types::PointerClass::Unsafe and typesEqual(*target, *payload)
9725 +
            permission == nil and sourceClass == class
9726 +
            and class <> types::PointerClass::Unsafe and typesEqual(*target, *payload)
9079 9727
        {
9080 9728
            return setNodeType(self, node, targetTy);
9081 9729
        }
9082 9730
        if typesEqual(sourceTy, targetTy) {
9083 9731
            return setNodeType(self, node, targetTy);
9391 10039
    let f = self.currentFn
9392 10040
        else throw emitError(self, node, ErrorKind::UnexpectedReturn);
9393 10041
    let expected = *f.returnType;
9394 10042
9395 10043
    if let val = retVal {
9396 -
        let _actualTy = try checkAssignable(self, val, expected);
10044 +
        let actualTy = try visit(self, val, expected);
10045 +
        if let source = referenceRegion(actualTy) {
10046 +
            if let destination = referenceRegion(expected);
10047 +
                not types::regionContains(source, destination)
10048 +
            {
10049 +
                let mut current = self.regionScope;
10050 +
                while let scope = current {
10051 +
                    let mut ownsSource = false;
10052 +
                    for region in scope.entries {
10053 +
                        if region.id == source.id {
10054 +
                            set ownsSource = true;
10055 +
                            break;
10056 +
                        }
10057 +
                    }
10058 +
                    if ownsSource {
10059 +
                        let mut lexical: ?*unsafe mut Scope = self.scope;
10060 +
                        while let localScope = lexical {
10061 +
                            if let owner = localScope.owner {
10062 +
                                if let case ast::NodeValue::RegionBlock { bindings, .. } =
10063 +
                                    owner.value
10064 +
                                {
10065 +
                                    if let case NodeExtra::Regions(blockRegions) =
10066 +
                                        self.nodeData.entries[owner.id].extra
10067 +
                                    {
10068 +
                                        if blockRegions.entries[0].id == source.id {
10069 +
                                            for bindingNode in bindings {
10070 +
                                                let case ast::NodeValue::RegionBinding(binding) =
10071 +
                                                    bindingNode.value
10072 +
                                                    else panic "resolveReturn: invalid region binding";
10073 +
                                                let case ast::NodeValue::AddressOf(address) =
10074 +
                                                    binding.value.value else continue;
10075 +
                                                if let cellTy =
10076 +
                                                    try inferCellPayload(self, address.target)
10077 +
                                                {
10078 +
                                                    if let case Type::Cell {
10079 +
                                                        permission: controlled,
10080 +
                                                        ..
10081 +
                                                    } = cellTy; controlled <> nil {
10082 +
                                                        throw emitError(
10083 +
                                                            self,
10084 +
                                                            val,
10085 +
                                                            ErrorKind::RegionEscape(source.name),
10086 +
                                                        );
10087 +
                                                    }
10088 +
                                                }
10089 +
                                            }
10090 +
                                            break;
10091 +
                                        }
10092 +
                                    }
10093 +
                                }
10094 +
                            }
10095 +
                            set lexical = localScope.parent;
10096 +
                        }
10097 +
                        break;
10098 +
                    }
10099 +
                    set current = scope.parent;
10100 +
                }
10101 +
            }
10102 +
        }
10103 +
        let _ = try expectAssignable(self, expected, actualTy, val);
10104 +
        if isRefType(expected) and isMutablePointerLike(expected) and
10105 +
            isMutablePointerLike(actualTy)
10106 +
        {
10107 +
            if not try canMutateThrough(self, val) {
10108 +
                throw emitError(self, val, ErrorKind::ImmutableBinding);
10109 +
            }
10110 +
        }
9397 10111
    } else if expected <> Type::Void {
9398 10112
        throw emitTypeMismatch(self, node, TypeMismatch { expected, actual: Type::Void });
9399 10113
    }
9400 10114
    // In throwing functions, return values are wrapped in the success variant.
9401 10115
    if f.throwList.len > 0 {
9739 10453
/// Convert a type signature node into a type value.
9740 10454
unsafe fn resolveTypeSig 'arena (self: &mut Resolver 'arena, node: *ast::Node, sig: ast::TypeSig) -> Type
9741 10455
    throws (ResolveError)
9742 10456
{
9743 10457
    match sig {
9744 -
        case ast::TypeSig::Cell { class, payload } => {
10458 +
        case ast::TypeSig::Cell { class, permission, payload } => {
9745 10459
            let inner = try infer(self, payload);
9746 10460
            try ensureStorableType(self, node, inner);
10461 +
            let mut permissionRegion: ?*unsafe types::Region = nil;
10462 +
            if let permissionNode = permission {
10463 +
                set permissionRegion = try resolveRegion(self, permissionNode);
10464 +
            }
9747 10465
            let allocator = alloc::arenaAllocator(self.arena);
9748 10466
            self.cellChecks.append(CellCheck {
9749 -
                node, payload: inner, regions: self.regionScope, moduleId: self.currentMod,
10467 +
                node,
10468 +
                payload: inner,
10469 +
                permission: permissionRegion,
10470 +
                regions: self.regionScope,
10471 +
                moduleId: self.currentMod,
9750 10472
            }, allocator);
9751 -
            return Type::Cell { class: resolvePointerClass(class), payload: allocType(self, inner) };
10473 +
            return Type::Cell {
10474 +
                class: resolvePointerClass(class),
10475 +
                permission: permissionRegion,
10476 +
                payload: allocType(self, inner),
10477 +
            };
9752 10478
        }
9753 10479
        case ast::TypeSig::RegionRef { region, type } => {
9754 10480
            let identity = try resolveRegion(self, region);
9755 10481
            let base = try infer(self, type);
9756 10482
            match base {
9757 -
                case Type::Cell { payload, .. } =>
9758 -
                    return Type::Cell { class: types::PointerClass::Region(identity), payload },
10483 +
                case Type::Cell { permission, payload, .. } =>
10484 +
                    return Type::Cell {
10485 +
                        class: types::PointerClass::Region(identity), permission, payload,
10486 +
                    },
9759 10487
                case Type::Pointer { target, mutable, .. } =>
9760 10488
                    return Type::Pointer { class: types::PointerClass::Region(identity), target, mutable },
9761 10489
                case Type::Slice { item, mutable, .. } =>
9762 10490
                    return Type::Slice { class: types::PointerClass::Region(identity), item, mutable },
9763 10491
                case Type::TraitObject { traitInfo, mutable, .. } =>
10102 10830
        loopBackLoans: [0; MAX_LINEAR_LOOP_DEPTH],
10103 10831
        loopExitLoans: [0; MAX_LINEAR_LOOP_DEPTH],
10104 10832
        loopRegions: [nil; MAX_LINEAR_LOOP_DEPTH],
10105 10833
        loans: [place; MAX_LINEAR_BINDINGS],
10106 10834
        loanLen: 0,
10107 -
        locals: [LocalLoan { binding: nil, place, exclusive: false }; MAX_LINEAR_BINDINGS],
10835 +
        locals: [LocalLoan {
10836 +
            binding: nil, place, exclusive: false, permission: nil, storage: nil,
10837 +
        }; MAX_LINEAR_BINDINGS],
10108 10838
        localLen: 0,
10839 +
        authorityPermissions: [nil; MAX_LINEAR_BINDINGS],
10840 +
        authorityBindings: [nil; MAX_LINEAR_BINDINGS],
10841 +
        authorityExclusive: [false; MAX_LINEAR_BINDINGS],
10842 +
        authorityLen: 0,
10843 +
        payloadAddress: nil,
10844 +
        witnessPermission: nil,
10109 10845
        loopMarks: [0; MAX_LINEAR_LOOP_DEPTH],
10110 10846
        loopAvailable: [0; MAX_LINEAR_LOOP_DEPTH],
10111 10847
        loopExitAvailable: [0; MAX_LINEAR_LOOP_DEPTH],
10112 10848
        loopHasNaturalExit: [false; MAX_LINEAR_LOOP_DEPTH],
10113 10849
        loopBreakSeen: [false; MAX_LINEAR_LOOP_DEPTH],
10146 10882
/// Return whether a tracked binding is still available.
10147 10883
fn linearBindingAvailable(env: &LinearEnv, index: u32) -> bool {
10148 10884
    return (env.available & ((1 as u64) << (index as u64))) <> 0;
10149 10885
}
10150 10886
10887 +
/// Find the newest live authority for a cell permission.
10888 +
unsafe fn findCellAuthority 'arena 'checking (
10889 +
    checker: &LinearChecker 'arena 'checking,
10890 +
    env: &LinearEnv,
10891 +
    permission: *unsafe types::Region,
10892 +
) -> ?u32 where 'arena: 'checking {
10893 +
    let mut i = checker.authorityLen;
10894 +
    while i > 0 {
10895 +
        set i -= 1;
10896 +
        let candidate = checker.authorityPermissions[i] else continue;
10897 +
        if candidate.id <> permission.id {
10898 +
            continue;
10899 +
        }
10900 +
        let binding = checker.authorityBindings[i]
10901 +
            else panic "findCellAuthority: missing authority binding";
10902 +
        if let bindingIndex = findLinearBinding(env, binding.id);
10903 +
            not linearBindingAvailable(env, bindingIndex)
10904 +
        {
10905 +
            continue;
10906 +
        }
10907 +
        return i;
10908 +
    }
10909 +
    return nil;
10910 +
}
10911 +
10151 10912
/// Add a local binding when its resolved type moves by value.
10152 10913
unsafe fn addLinearBinding 'arena 'checking (checker: &mut LinearChecker 'arena 'checking, env: &mut LinearEnv, node: *ast::Node)
10153 10914
    throws (ResolveError) where 'arena: 'checking
10154 10915
{
10155 10916
    let sym = symbolFor(checker.resolver, node) else return;
10545 11306
        return true;
10546 11307
    }
10547 11308
    let source = localReferenceSource(root) else return false;
10548 11309
    return usesLocalLoan(self, source, binding);
10549 11310
}
10550 -
10551 11311
/// Reject accesses that conflict with a reference in an active lexical scope.
10552 11312
unsafe fn checkLocalLoans 'arena 'checking (checker: &mut LinearChecker 'arena 'checking, env: &LinearEnv, node: *ast::Node, exclusive: bool)
10553 11313
    throws (ResolveError) where 'arena: 'checking
10554 11314
{
10555 11315
    let place = borrowPlace(checker.resolver, node);
10556 -
    let root = place.root else return;
10557 -
    for i in 0..checker.regionalLen {
10558 -
        if (env.regionalLoans & ((1 as u64) << (i as u64))) == 0 {
10559 -
            continue;
10560 -
        }
10561 -
        let loan = regionalLoan(checker, i);
10562 -
        if (exclusive or loan.exclusive) and placesOverlap(&place, &loan.place)
10563 -
            and not usesRegionalLoan(checker.resolver, node, loan.source)
10564 -
        {
10565 -
            throw emitError(checker.resolver, node, ErrorKind::BorrowConflict(root.name));
11316 +
    let root = place.root;
11317 +
    if let placeRoot = root {
11318 +
        for i in 0..checker.regionalLen {
11319 +
            if (env.regionalLoans & ((1 as u64) << (i as u64))) == 0 {
11320 +
                continue;
11321 +
            }
11322 +
            let loan = regionalLoan(checker, i);
11323 +
            if (exclusive or loan.exclusive) and placesOverlap(&place, &loan.place)
11324 +
                and not usesRegionalLoan(checker.resolver, node, loan.source)
11325 +
            {
11326 +
                throw emitError(
11327 +
                    checker.resolver, node, ErrorKind::BorrowConflict(placeRoot.name),
11328 +
                );
11329 +
            }
10566 11330
        }
10567 11331
    }
11332 +
    let mut accessRegion: ?*unsafe types::Region = nil;
11333 +
    if let ty = typeFor(checker.resolver, node) {
11334 +
        set accessRegion = referenceRegion(ty);
11335 +
    }
11336 +
    if let cellTy = try explicitCellPayload(checker.resolver, node) {
11337 +
        let case Type::Cell { permission, .. } = cellTy
11338 +
            else panic "checkLocalLoans: invalid cell payload";
11339 +
        set accessRegion = permission;
11340 +
    } else if let cellTy = try inferCellPayload(checker.resolver, node) {
11341 +
        let case Type::Cell { permission, .. } = cellTy
11342 +
            else panic "checkLocalLoans: invalid cell payload";
11343 +
        set accessRegion = permission;
11344 +
    }
10568 11345
    for i in 0..checker.localLen {
10569 11346
        let loan = checker.locals[i];
10570 11347
        let mut throughBinding = false;
10571 11348
        if let binding = loan.binding {
10572 11349
            set throughBinding = usesLocalLoan(checker.resolver, node, binding);
10573 11350
        }
10574 -
        if (exclusive or loan.exclusive) and placesOverlap(&place, &loan.place)
11351 +
        if let placeRoot = root;
11352 +
            (exclusive or loan.exclusive) and placesOverlap(&place, &loan.place)
10575 11353
            and not throughBinding
10576 11354
        {
10577 -
            throw emitError(checker.resolver, node, ErrorKind::BorrowConflict(root.name));
11355 +
            throw emitError(
11356 +
                checker.resolver, node, ErrorKind::BorrowConflict(placeRoot.name),
11357 +
            );
11358 +
        }
11359 +
        let permission = loan.permission else continue;
11360 +
        let region = accessRegion else continue;
11361 +
        let mut identityMatches = permission.id == region.id;
11362 +
        if let storage = loan.storage; storage.id == region.id {
11363 +
            set identityMatches = true;
11364 +
        }
11365 +
        if not identityMatches or not (exclusive or loan.exclusive) or throughBinding {
11366 +
            continue;
11367 +
        }
11368 +
        let mut name = permission.name;
11369 +
        if let placeRoot = root {
11370 +
            set name = placeRoot.name;
10578 11371
        }
11372 +
        throw emitError(checker.resolver, node, ErrorKind::BorrowConflict(name));
11373 +
    }
11374 +
}
11375 +
11376 +
/// Return cell metadata for an explicit payload borrow through transparent wrappers.
11377 +
unsafe fn explicitCellPayload 'arena (
11378 +
    self: &mut Resolver 'arena, node: *ast::Node
11379 +
) -> ?Type throws (ResolveError) {
11380 +
    match node.value {
11381 +
        case ast::NodeValue::AddressOf(address) =>
11382 +
            return try inferCellPayload(self, address.target),
11383 +
        case ast::NodeValue::As(cast) =>
11384 +
            return try explicitCellPayload(self, cast.value),
11385 +
        case ast::NodeValue::RegionApply { value, .. } =>
11386 +
            return try explicitCellPayload(self, value),
11387 +
        else => return nil,
10579 11388
    }
10580 11389
}
10581 11390
10582 11391
/// Retain source storage for local borrows and region headers.
10583 11392
unsafe fn addLocalLoan 'arena 'checking (checker: &mut LinearChecker 'arena 'checking, env: &LinearEnv, node: *ast::Node, binding: ast::Let)
10613 11422
                }
10614 11423
            }
10615 11424
        }
10616 11425
    }
10617 11426
    try checkLocalLoans(checker, env, binding.value, exclusive);
10618 -
    set checker.locals[checker.localLen] = LocalLoan { binding: sym, place, exclusive };
11427 +
    let mut permission: ?*unsafe types::Region = nil;
11428 +
    let mut storage: ?*unsafe types::Region = nil;
11429 +
    if let cellTy = try explicitCellPayload(checker.resolver, binding.value) {
11430 +
        let case Type::Cell {
11431 +
            class, permission: cellPermission, ..
11432 +
        } = cellTy else panic "addLocalLoan: invalid cell payload";
11433 +
        set permission = cellPermission;
11434 +
        if let case types::PointerClass::Region(region) = class {
11435 +
            set storage = region;
11436 +
        }
11437 +
    }
11438 +
    set checker.locals[checker.localLen] = LocalLoan {
11439 +
        binding: sym, place, exclusive, permission, storage,
11440 +
    };
10619 11441
    set checker.localLen += 1;
10620 11442
}
10621 11443
10622 11444
/// Protect storage borrowed by a pointer pattern until its bindings leave scope.
10623 11445
unsafe fn addPatternLoan 'arena 'checking (checker: &mut LinearChecker 'arena 'checking, subject: *ast::Node)
10663 11485
        case Type::TraitObject { class, .. } => return class == types::PointerClass::Ref,
10664 11486
        else => return false,
10665 11487
    }
10666 11488
}
10667 11489
11490 +
/// Return whether a type carries one region in the requested compile-time role.
11491 +
/// Applied nominal visits are generation- and role-marked; unapplied nominals
11492 +
/// cannot carry the queried free region and require no member traversal.
11493 +
unsafe fn typeHasRegionRole 'arena (
11494 +
    self: &mut Resolver 'arena,
11495 +
    ty: Type,
11496 +
    region: *unsafe types::Region,
11497 +
    role: RegionTypeRole,
11498 +
    generation: u32,
11499 +
) -> bool {
11500 +
    if role == RegionTypeRole::Reference {
11501 +
        if let dependency = referenceRegion(ty); dependency == region {
11502 +
            return true;
11503 +
        }
11504 +
    }
11505 +
    match ty {
11506 +
        case Type::Cell { permission, payload, .. } => {
11507 +
            if role == RegionTypeRole::Retention {
11508 +
                return typeHasRegionRole(
11509 +
                    self, *payload, region, RegionTypeRole::Reference, generation,
11510 +
                ) or typeHasRegionRole(
11511 +
                    self, *payload, region, RegionTypeRole::Retention, generation,
11512 +
                );
11513 +
            }
11514 +
            if role == RegionTypeRole::CellPermission {
11515 +
                if let identity = permission; identity == region {
11516 +
                    return true;
11517 +
                }
11518 +
            }
11519 +
            return typeHasRegionRole(
11520 +
                self, *payload, region, role, generation,
11521 +
            );
11522 +
        }
11523 +
        case Type::Session(identity) =>
11524 +
            return role == RegionTypeRole::Retention
11525 +
                and types::regionContains(region, identity),
11526 +
        case Type::Pointer { target, .. } =>
11527 +
            return typeHasRegionRole(
11528 +
                self, *target, region, role, generation,
11529 +
            ),
11530 +
        case Type::Slice { item, .. } =>
11531 +
            return typeHasRegionRole(
11532 +
                self, *item, region, role, generation,
11533 +
            ),
11534 +
        case Type::Array(array) =>
11535 +
            return typeHasRegionRole(
11536 +
                self, *array.item, region, role, generation,
11537 +
            ),
11538 +
        case Type::Optional(inner) =>
11539 +
            return typeHasRegionRole(
11540 +
                self, *inner, region, role, generation,
11541 +
            ),
11542 +
        case Type::Range { start, end } => {
11543 +
            if let startType = start;
11544 +
                typeHasRegionRole(
11545 +
                    self, *startType, region, role, generation,
11546 +
                )
11547 +
            {
11548 +
                return true;
11549 +
            }
11550 +
            if let endType = end {
11551 +
                return typeHasRegionRole(
11552 +
                    self, *endType, region, role, generation,
11553 +
                );
11554 +
            }
11555 +
            return false;
11556 +
        }
11557 +
        case Type::Nominal(info) => {
11558 +
            let applied = nominalApplication(info) else return false;
11559 +
            if not visitNominalApplication(applied, generation, role) {
11560 +
                // This application and role have no unvisited members.
11561 +
                return false;
11562 +
            }
11563 +
            match *info {
11564 +
                case NominalType::Record(recordType) => {
11565 +
                    for field in recordType.fields {
11566 +
                        if typeHasRegionRole(
11567 +
                            self, field.fieldType, region, role, generation,
11568 +
                        ) {
11569 +
                            return true;
11570 +
                        }
11571 +
                    }
11572 +
                }
11573 +
                case NominalType::Union(unionType) => {
11574 +
                    for variant in unionType.variants {
11575 +
                        if typeHasRegionRole(
11576 +
                            self, variant.valueType, region, role, generation,
11577 +
                        ) {
11578 +
                            return true;
11579 +
                        }
11580 +
                    }
11581 +
                }
11582 +
                // Linear checking normally sees completed applications. Deny
11583 +
                // reuse without treating an unknown view as permission proof.
11584 +
                case NominalType::Placeholder(_), NominalType::Resolving(_),
11585 +
                     NominalType::Application(_) =>
11586 +
                    return role <> RegionTypeRole::CellPermission,
11587 +
            }
11588 +
            return false;
11589 +
        }
11590 +
        case Type::Fn(info) => {
11591 +
            for parameter in info.paramTypes {
11592 +
                if typeHasRegionRole(
11593 +
                    self, *parameter, region, role, generation,
11594 +
                ) {
11595 +
                    return true;
11596 +
                }
11597 +
            }
11598 +
            for error in info.throwList {
11599 +
                if typeHasRegionRole(
11600 +
                    self, *error, region, role, generation,
11601 +
                ) {
11602 +
                    return true;
11603 +
                }
11604 +
            }
11605 +
            return typeHasRegionRole(
11606 +
                self, *info.returnType, region, role, generation,
11607 +
            );
11608 +
        }
11609 +
        else => return false,
11610 +
    }
11611 +
}
11612 +
11613 +
/// Classify one call argument from the instantiated function contract.
11614 +
/// Regional mutable authority is call-borrowed only when the contract uses its
11615 +
/// region as cell permission and no result, error, other input, or mutable
11616 +
/// receiver can retain a reference carrying that region.
11617 +
unsafe fn callParameterUse 'arena (
11618 +
    self: &mut Resolver 'arena,
11619 +
    info: *FnType,
11620 +
    parameterIndex: u32,
11621 +
    receiver: ?Type,
11622 +
    receiverMutable: bool,
11623 +
) -> LinearUse {
11624 +
    let parameter = *info.paramTypes[parameterIndex];
11625 +
    if isBorrowedReferenceParameter(parameter) {
11626 +
        return LinearUse::Borrow;
11627 +
    }
11628 +
    let case Type::Pointer {
11629 +
        class: types::PointerClass::Region(region), mutable: true, ..
11630 +
    } = parameter else return LinearUse::Consume;
11631 +
11632 +
    let permissionGeneration = nextNominalTraversalGeneration(self);
11633 +
    let mut hasPermission = false;
11634 +
    if let receiverType = receiver {
11635 +
        set hasPermission = typeHasRegionRole(
11636 +
            self, receiverType, region, RegionTypeRole::CellPermission,
11637 +
            permissionGeneration,
11638 +
        );
11639 +
    }
11640 +
    if not hasPermission {
11641 +
        for candidate in info.paramTypes {
11642 +
            if typeHasRegionRole(
11643 +
                self, *candidate, region, RegionTypeRole::CellPermission,
11644 +
                permissionGeneration,
11645 +
            ) {
11646 +
                set hasPermission = true;
11647 +
                break;
11648 +
            }
11649 +
        }
11650 +
    }
11651 +
    if not hasPermission {
11652 +
        for error in info.throwList {
11653 +
            if typeHasRegionRole(
11654 +
                self, *error, region, RegionTypeRole::CellPermission,
11655 +
                permissionGeneration,
11656 +
            ) {
11657 +
                set hasPermission = true;
11658 +
                break;
11659 +
            }
11660 +
        }
11661 +
    }
11662 +
    if not hasPermission {
11663 +
        set hasPermission = typeHasRegionRole(
11664 +
            self, *info.returnType, region, RegionTypeRole::CellPermission,
11665 +
            permissionGeneration,
11666 +
        );
11667 +
    }
11668 +
    if not hasPermission {
11669 +
        return LinearUse::Consume;
11670 +
    }
11671 +
11672 +
    // Results and thrown values outlive the call directly.
11673 +
    let resultGeneration = nextNominalTraversalGeneration(self);
11674 +
    if typeHasRegionRole(
11675 +
        self, *info.returnType, region, RegionTypeRole::Reference,
11676 +
        resultGeneration,
11677 +
    ) {
11678 +
        return LinearUse::Consume;
11679 +
    }
11680 +
    for error in info.throwList {
11681 +
        if typeHasRegionRole(
11682 +
            self, *error, region, RegionTypeRole::Reference, resultGeneration,
11683 +
        ) {
11684 +
            return LinearUse::Consume;
11685 +
        }
11686 +
    }
11687 +
11688 +
    // A mutable input can store the authority reference, while cells and
11689 +
    // sessions provide interior retention even through an otherwise shared
11690 +
    // contract position. Exclude the authority parameter itself.
11691 +
    for candidate, i in info.paramTypes {
11692 +
        if i == parameterIndex {
11693 +
            continue;
11694 +
        }
11695 +
        let retentionGeneration = nextNominalTraversalGeneration(self);
11696 +
        if typeHasRegionRole(
11697 +
            self, *candidate, region, RegionTypeRole::Retention,
11698 +
            retentionGeneration,
11699 +
        ) {
11700 +
            return LinearUse::Consume;
11701 +
        }
11702 +
        let referenceGeneration = nextNominalTraversalGeneration(self);
11703 +
        if typeHasRegionRole(
11704 +
            self, *candidate, region, RegionTypeRole::Reference,
11705 +
            referenceGeneration,
11706 +
        ) and isExclusiveArgument(*candidate) {
11707 +
            return LinearUse::Consume;
11708 +
        }
11709 +
    }
11710 +
11711 +
    if let receiverType = receiver {
11712 +
        let retentionGeneration = nextNominalTraversalGeneration(self);
11713 +
        if typeHasRegionRole(
11714 +
            self, receiverType, region, RegionTypeRole::Retention,
11715 +
            retentionGeneration,
11716 +
        ) {
11717 +
            return LinearUse::Consume;
11718 +
        }
11719 +
        if receiverMutable {
11720 +
            let referenceGeneration = nextNominalTraversalGeneration(self);
11721 +
            if typeHasRegionRole(
11722 +
                self, receiverType, region, RegionTypeRole::Reference,
11723 +
                referenceGeneration,
11724 +
            ) {
11725 +
                return LinearUse::Consume;
11726 +
            }
11727 +
        }
11728 +
    }
11729 +
    return LinearUse::Borrow;
11730 +
}
11731 +
10668 11732
/// Return whether a parameter can mutate or consume its argument's storage.
10669 11733
unsafe fn isExclusiveArgument(ty: Type) -> bool {
10670 11734
    match ty {
10671 11735
        case Type::Pointer { mutable, .. } => return mutable,
10672 11736
        case Type::Slice { mutable, .. } => return mutable,
10724 11788
    env: &mut LinearEnv,
10725 11789
    node: *ast::Node,
10726 11790
) throws (ResolveError) where 'arena: 'checking {
10727 11791
    let start = env.len;
10728 11792
    let localStart = checker.localLen;
11793 +
    let authorityStart = checker.authorityLen;
10729 11794
    let case ast::NodeValue::Block(block) = node.value
10730 11795
        else panic "checkLinearBlock: expected block";
10731 11796
    for stmt in block.statements {
10732 11797
        if env.terminated {
10733 11798
            break;
10734 11799
        }
10735 11800
        try checkLinearNode(checker, env, stmt, LinearUse::Discard);
10736 11801
    }
10737 11802
    try finishLinearScope(checker, env, start);
10738 11803
    set checker.localLen = localStart;
11804 +
    set checker.authorityLen = authorityStart;
10739 11805
}
10740 11806
10741 11807
/// Push a repeated-control-flow boundary.
10742 11808
/// Initialize all loop state at this depth before increasing `loopDepth`.
10743 11809
fn enterLinearLoop 'arena 'checking (checker: &mut LinearChecker 'arena 'checking, env: &LinearEnv) where 'arena: 'checking {
10946 12012
        }
10947 12013
        else => {}
10948 12014
    }
10949 12015
    try checkLinearNode(checker, env, call.callee, LinearUse::Observe);
10950 12016
    let mut fnInfo: ?*FnType = nil;
10951 -
    match checker.resolver.nodeData.entries[node.id].extra {
10952 -
        case NodeExtra::TraitMethodCall { traitInfo, methodIndex } =>
10953 -
            set fnInfo = traitInfo.methods[methodIndex].fnType,
10954 -
        case NodeExtra::MethodCall { method } => set fnInfo = method.fnType,
10955 -
        else => {
10956 -
            if let calleeTy = typeFor(checker.resolver, call.callee) {
10957 -
                if let case Type::Fn(info) = calleeTy {
10958 -
                    set fnInfo = info;
10959 -
                }
10960 -
            }
12017 +
    if let calleeTy = typeFor(checker.resolver, call.callee) {
12018 +
        if let case Type::Fn(info) = calleeTy {
12019 +
            set fnInfo = info;
12020 +
        }
12021 +
    }
12022 +
    if fnInfo == nil {
12023 +
        match checker.resolver.nodeData.entries[node.id].extra {
12024 +
            case NodeExtra::TraitMethodCall { traitInfo, methodIndex } =>
12025 +
                set fnInfo = traitInfo.methods[methodIndex].fnType,
12026 +
            case NodeExtra::MethodCall { method } => set fnInfo = method.fnType,
12027 +
            else => {}
10961 12028
        }
10962 12029
    }
10963 12030
    let info = fnInfo else {
10964 12031
        for arg in call.args {
10965 12032
            try checkLinearNode(checker, env, arg, LinearUse::Consume);
10966 12033
        }
10967 12034
        return;
10968 12035
    };
10969 12036
    let mut arguments: [?CallArgument; MAX_FN_PARAMS + 1] = [nil; MAX_FN_PARAMS + 1];
10970 12037
    let mut argumentsLen: u32 = 0;
12038 +
    let mut contractReceiver: ?Type = nil;
12039 +
    let mut contractReceiverMutable = false;
10971 12040
10972 12041
    // Method function types exclude their implicit receiver. Account for it
10973 12042
    // explicitly so owning receivers are consumed and reference receivers
10974 12043
    // participate in call-scoped loan conflict checks.
10975 12044
    if let case ast::NodeValue::FieldAccess(access) = call.callee.value {
10989 12058
                set haveReceiver = true;
10990 12059
            }
10991 12060
            else => {}
10992 12061
        }
10993 12062
        if haveReceiver {
12063 +
            if let receiverType = typeFor(checker.resolver, access.parent) {
12064 +
                set contractReceiver = autoDeref(receiverType);
12065 +
            }
12066 +
            set contractReceiverMutable = receiverMutable;
10994 12067
            try checkLocalLoans(checker, env, access.parent,
10995 12068
                receiverMutable or receiverClass == types::PointerClass::Owned);
10996 12069
            if receiverMutable or receiverClass == types::PointerClass::Owned {
10997 12070
                try checkPatternLoan(checker, access.parent);
10998 12071
            }
11031 12104
            }
11032 12105
            set arguments[argumentsLen] = CallArgument { node: arg, exclusive: argExclusive };
11033 12106
            set argumentsLen += 1;
11034 12107
        }
11035 12108
        try checkLocalLoans(checker, env, arg, argExclusive);
11036 -
        if isBorrowedReferenceParameter(expected) {
11037 -
            try checkLinearNode(checker, env, arg, LinearUse::Borrow);
11038 -
        } else {
11039 -
            try checkLinearNode(checker, env, arg, LinearUse::Consume);
11040 -
        }
12109 +
        let argumentUse = callParameterUse(
12110 +
            checker.resolver, info, i, contractReceiver, contractReceiverMutable,
12111 +
        );
12112 +
        try checkLinearNode(checker, env, arg, argumentUse);
11041 12113
        if isRefType(expected) and createsExplicitBorrow(arg) {
11042 12114
            try retainCallLoan(checker, arg, argExclusive);
11043 12115
        }
11044 12116
    }
11045 12117
    set checker.localLen = localStart;
11120 12192
        return;
11121 12193
    }
11122 12194
    if checker.localLen >= MAX_LINEAR_BINDINGS {
11123 12195
        throw emitError(checker.resolver, node, ErrorKind::Internal);
11124 12196
    }
11125 -
    set checker.locals[checker.localLen] = LocalLoan { binding: nil, place, exclusive };
12197 +
    let mut permission: ?*unsafe types::Region = nil;
12198 +
    let mut storage: ?*unsafe types::Region = nil;
12199 +
    if let cellTy = try explicitCellPayload(checker.resolver, node) {
12200 +
        let case Type::Cell {
12201 +
            class, permission: cellPermission, ..
12202 +
        } = cellTy else panic "retainCallLoan: invalid cell payload";
12203 +
        set permission = cellPermission;
12204 +
        if let case types::PointerClass::Region(region) = class {
12205 +
            set storage = region;
12206 +
        }
12207 +
    }
12208 +
    set checker.locals[checker.localLen] = LocalLoan {
12209 +
        binding: nil, place, exclusive, permission, storage,
12210 +
    };
11126 12211
    set checker.localLen += 1;
11127 12212
}
11128 12213
11129 12214
/// Check a pattern conditional. Linear scrutinees require an exhaustive match.
11130 12215
unsafe fn checkLinearIfLet 'arena 'checking (
11391 12476
    if usage <> LinearUse::Locate {
11392 12477
        match node.value {
11393 12478
            case ast::NodeValue::Ident(_), ast::NodeValue::ScopeAccess(_),
11394 12479
                 ast::NodeValue::FieldAccess(_), ast::NodeValue::Subscript { .. },
11395 12480
                 ast::NodeValue::Deref(_) => {
11396 -
                let mut exclusive = usage == LinearUse::Place and not isCellDeref(checker.resolver, node);
12481 +
                let mut exclusive = usage == LinearUse::Place
12482 +
                    and not isCellDeref(checker.resolver, node);
11397 12483
                if usage == LinearUse::Consume {
11398 12484
                    if let ty = typeFor(checker.resolver, node) {
11399 12485
                        set exclusive = isExclusiveArgument(ty);
11400 12486
                    }
11401 12487
                }
12488 +
                if let cellTy = try inferCellPayload(checker.resolver, node) {
12489 +
                    let case Type::Cell { permission: controlled, .. } = cellTy
12490 +
                        else panic "checkLinearNode: invalid cell payload";
12491 +
                    if let permission = controlled {
12492 +
                        let permissionExclusive = usage == LinearUse::Place;
12493 +
                        for i in 0..checker.localLen {
12494 +
                            let loan = checker.locals[i];
12495 +
                            if let loanPermission = loan.permission;
12496 +
                                loanPermission.id == permission.id
12497 +
                                and (permissionExclusive or loan.exclusive)
12498 +
                            {
12499 +
                                throw emitError(
12500 +
                                    checker.resolver, node,
12501 +
                                    ErrorKind::BorrowConflict(permission.name),
12502 +
                                );
12503 +
                            }
12504 +
                        }
12505 +
                        let index = findCellAuthority(checker, env, permission)
12506 +
                            else throw emitError(
12507 +
                                checker.resolver, node,
12508 +
                                ErrorKind::CellPermissionRequired(permission.name),
12509 +
                            );
12510 +
                        if permissionExclusive and not checker.authorityExclusive[index] {
12511 +
                            throw emitError(
12512 +
                                checker.resolver, node,
12513 +
                                ErrorKind::CellPermissionRequired(permission.name),
12514 +
                            );
12515 +
                        }
12516 +
                    }
12517 +
                }
11402 12518
                try checkLocalLoans(checker, env, node, exclusive);
11403 12519
            }
11404 12520
            else => {}
11405 12521
        }
11406 12522
    }
11430 12546
                if checker.resolver.errors.len > 0 {
11431 12547
                    return;
11432 12548
                }
11433 12549
                panic "checkLinearNode: missing region scope";
11434 12550
            };
11435 -
            set checker.regions = scope;
11436 12551
            let start = env.len;
11437 12552
            let localStart = checker.localLen;
12553 +
            let authorityStart = checker.authorityLen;
12554 +
            let mut reborrowSources: [?*ast::Node; MAX_LINEAR_BINDINGS] =
12555 +
                [nil; MAX_LINEAR_BINDINGS];
12556 +
            let mut reborrowPermissions: [?*unsafe types::Region; MAX_LINEAR_BINDINGS] =
12557 +
                [nil; MAX_LINEAR_BINDINGS];
12558 +
            let mut reborrowExclusive: [bool; MAX_LINEAR_BINDINGS] =
12559 +
                [false; MAX_LINEAR_BINDINGS];
12560 +
            let mut reborrowLen: u32 = 0;
11438 12561
            for bindingNode in bindings {
11439 12562
                let case ast::NodeValue::RegionBinding(binding) = bindingNode.value
11440 12563
                    else panic "checkLinearNode: invalid borrow binding";
12564 +
                let case ast::NodeValue::AddressOf(address) = binding.value.value
12565 +
                    else continue;
12566 +
                if address.kind == ast::AddressKind::Cell {
12567 +
                    continue;
12568 +
                }
12569 +
                let case ast::NodeValue::Deref(source) = address.target.value
12570 +
                    else continue;
12571 +
                let sourceTy = typeFor(checker.resolver, source) else continue;
12572 +
                let case Type::Pointer {
12573 +
                    class: types::PointerClass::Region(permission),
12574 +
                    mutable: true,
12575 +
                    ..
12576 +
                } = sourceTy else continue;
12577 +
                let authorityIndex = findCellAuthority(checker, env, permission)
12578 +
                    else continue;
12579 +
                if not checker.authorityExclusive[authorityIndex] {
12580 +
                    continue;
12581 +
                }
12582 +
                assert reborrowLen < MAX_LINEAR_BINDINGS,
12583 +
                    "checkLinearNode: permission reborrow overflow";
12584 +
                set reborrowSources[reborrowLen] = binding.value;
12585 +
                set reborrowPermissions[reborrowLen] = permission;
12586 +
                set reborrowExclusive[reborrowLen] =
12587 +
                    address.kind == ast::AddressKind::Mutable;
12588 +
                set reborrowLen += 1;
12589 +
            }
12590 +
            set checker.regions = scope;
12591 +
            for bindingNode in bindings {
12592 +
                let case ast::NodeValue::RegionBinding(binding) = bindingNode.value
12593 +
                    else panic "checkLinearNode: invalid borrow binding";
12594 +
                let case ast::NodeValue::AddressOf(address) = binding.value.value
12595 +
                    else panic "checkLinearNode: invalid borrow source";
12596 +
                if let cellTy = try inferCellPayload(checker.resolver, address.target) {
12597 +
                    let case Type::Cell { permission: controlled, .. } = cellTy
12598 +
                        else panic "checkLinearNode: invalid cell payload";
12599 +
                    if let permission = controlled {
12600 +
                        let exclusive = address.kind == ast::AddressKind::Mutable;
12601 +
                        let mut matched = false;
12602 +
                        for i in 0..reborrowLen {
12603 +
                            let candidate = reborrowPermissions[i]
12604 +
                                else panic "checkLinearNode: missing reborrow permission";
12605 +
                            if candidate.id == permission.id
12606 +
                                and reborrowExclusive[i] == exclusive
12607 +
                            {
12608 +
                                set matched = true;
12609 +
                                break;
12610 +
                            }
12611 +
                        }
12612 +
                        if not matched {
12613 +
                            throw emitError(
12614 +
                                checker.resolver, binding.value,
12615 +
                                ErrorKind::CellPermissionRequired(permission.name),
12616 +
                            );
12617 +
                        }
12618 +
                        set checker.payloadAddress = binding.value;
12619 +
                    }
12620 +
                }
12621 +
                for i in 0..reborrowLen {
12622 +
                    let source = reborrowSources[i]
12623 +
                        else panic "checkLinearNode: missing authority reborrow";
12624 +
                    if source == binding.value {
12625 +
                        set checker.witnessPermission = reborrowPermissions[i];
12626 +
                        break;
12627 +
                    }
12628 +
                }
11441 12629
                try checkLinearNode(checker, env, binding.value, LinearUse::Consume);
11442 12630
                if env.terminated {
11443 12631
                    break;
11444 12632
                }
11445 12633
                try addLinearBinding(checker, env, bindingNode);
11446 -
                try addLocalLoan(checker, env, bindingNode, ast::borrowBinding(binding));
12634 +
                let lexical = ast::borrowBinding(binding);
12635 +
                try addLocalLoan(checker, env, bindingNode, lexical);
12636 +
                let symbol = symbolFor(checker.resolver, bindingNode)
12637 +
                    else panic "checkLinearNode: missing region binding";
12638 +
                let mut permission = checker.witnessPermission;
12639 +
                let mut exclusive = address.kind == ast::AddressKind::Mutable;
12640 +
                if permission == nil {
12641 +
                    if let case SymbolData::Value {
12642 +
                        type: Type::Pointer {
12643 +
                            class: types::PointerClass::Region(region),
12644 +
                            mutable: true,
12645 +
                            ..
12646 +
                        },
12647 +
                        ..
12648 +
                    } = symbol.data {
12649 +
                        set permission = region;
12650 +
                        set exclusive = true;
12651 +
                    }
12652 +
                }
12653 +
                if let controlled = permission {
12654 +
                    if checker.authorityLen >= MAX_LINEAR_BINDINGS {
12655 +
                        throw emitError(checker.resolver, bindingNode, ErrorKind::Internal);
12656 +
                    }
12657 +
                    let index = checker.authorityLen;
12658 +
                    set checker.authorityPermissions[index] = controlled;
12659 +
                    set checker.authorityBindings[index] = symbol;
12660 +
                    set checker.authorityExclusive[index] = exclusive;
12661 +
                    set checker.authorityLen += 1;
12662 +
                }
12663 +
                set checker.payloadAddress = nil;
12664 +
                set checker.witnessPermission = nil;
11447 12665
            }
11448 12666
            try checkLinearBlock(checker, env, body);
11449 12667
            try finishLinearScope(checker, env, start);
11450 12668
            set checker.localLen = localStart;
12669 +
            set checker.authorityLen = authorityStart;
11451 12670
            set checker.regions = previousRegions;
11452 12671
            compactRegionalLoans(checker, env, previousRegions);
11453 12672
        }
11454 12673
        case ast::NodeValue::Block(_) => try checkLinearBlock(checker, env, node),
11455 12674
        case ast::NodeValue::Let(binding) => {
11472 12691
            if env.terminated {
11473 12692
                return;
11474 12693
            }
11475 12694
            try addLinearBinding(checker, env, node);
11476 12695
            try addLocalLoan(checker, env, node, binding);
12696 +
            if let symbol = symbolFor(checker.resolver, node) {
12697 +
                if let case SymbolData::Value {
12698 +
                    type: Type::Pointer {
12699 +
                        class: types::PointerClass::Region(permission),
12700 +
                        mutable: true,
12701 +
                        ..
12702 +
                    },
12703 +
                    ..
12704 +
                } = symbol.data {
12705 +
                    if checker.authorityLen >= MAX_LINEAR_BINDINGS {
12706 +
                        throw emitError(checker.resolver, node, ErrorKind::Internal);
12707 +
                    }
12708 +
                    let index = checker.authorityLen;
12709 +
                    set checker.authorityPermissions[index] = permission;
12710 +
                    set checker.authorityBindings[index] = symbol;
12711 +
                    set checker.authorityExclusive[index] = true;
12712 +
                    set checker.authorityLen += 1;
12713 +
                }
12714 +
            }
11477 12715
            expireAllocationLoans(checker, env, node, binding.value);
11478 12716
            if isUndefined {
11479 12717
                markLinearBindingUnavailable(checker.resolver, env, node);
11480 12718
            }
11481 12719
        }
11517 12755
        }
11518 12756
        case ast::NodeValue::RegionApply { value, .. } =>
11519 12757
            try checkLinearNode(checker, env, value, usage),
11520 12758
        case ast::NodeValue::Call(call) => try checkLinearCall(checker, env, node, call),
11521 12759
        case ast::NodeValue::AddressOf(addr) => {
12760 +
            if addr.kind == ast::AddressKind::Cell {
12761 +
                if let resultTy = typeFor(checker.resolver, node) {
12762 +
                    if let case Type::Cell { permission: controlled, .. } = resultTy {
12763 +
                        if let permission = controlled {
12764 +
                            let index = findCellAuthority(checker, env, permission)
12765 +
                                else throw emitError(
12766 +
                                    checker.resolver, node,
12767 +
                                    ErrorKind::CellPermissionRequired(permission.name),
12768 +
                                );
12769 +
                            if not checker.authorityExclusive[index] {
12770 +
                                throw emitError(
12771 +
                                    checker.resolver, node,
12772 +
                                    ErrorKind::CellPermissionRequired(permission.name),
12773 +
                                );
12774 +
                            }
12775 +
                        }
12776 +
                    }
12777 +
                }
12778 +
            }
12779 +
            if let cellTy = try inferCellPayload(checker.resolver, addr.target) {
12780 +
                let case Type::Cell { permission: controlled, .. } = cellTy
12781 +
                    else panic "checkLinearNode: invalid cell payload address";
12782 +
                if let permission = controlled {
12783 +
                    let mut headerValidated = false;
12784 +
                    if let allowed = checker.payloadAddress; allowed == node {
12785 +
                        set headerValidated = true;
12786 +
                    }
12787 +
                    if not headerValidated {
12788 +
                        let index = findCellAuthority(checker, env, permission)
12789 +
                            else throw emitError(
12790 +
                                checker.resolver, node,
12791 +
                                ErrorKind::CellPermissionRequired(permission.name),
12792 +
                            );
12793 +
                        if addr.kind == ast::AddressKind::Mutable
12794 +
                            and not checker.authorityExclusive[index]
12795 +
                        {
12796 +
                            throw emitError(
12797 +
                                checker.resolver, node,
12798 +
                                ErrorKind::CellPermissionRequired(permission.name),
12799 +
                            );
12800 +
                        }
12801 +
                    }
12802 +
                    let permissionExclusive = addr.kind == ast::AddressKind::Mutable;
12803 +
                    for i in 0..checker.localLen {
12804 +
                        let loan = checker.locals[i];
12805 +
                        if let loanPermission = loan.permission;
12806 +
                            loanPermission.id == permission.id
12807 +
                            and (permissionExclusive or loan.exclusive)
12808 +
                        {
12809 +
                            throw emitError(
12810 +
                                checker.resolver, node,
12811 +
                                ErrorKind::BorrowConflict(permission.name),
12812 +
                            );
12813 +
                        }
12814 +
                    }
12815 +
                }
12816 +
            }
11522 12817
            try checkLocalLoans(checker, env, addr.target, ast::isExclusiveAddress(addr));
11523 12818
            if ast::isExclusiveAddress(addr) {
11524 12819
                try checkPatternLoan(checker, addr.target);
11525 12820
            }
11526 12821
            let mut owner: ?*ast::Node = nil;
11538 12833
            }
11539 12834
            try addRegionalLoan(checker, env, node, addr);
11540 12835
        }
11541 12836
        case ast::NodeValue::Deref(target) => {
11542 12837
            if let resultTy = typeFor(checker.resolver, node) {
11543 -
                if isMoveOnly(resultTy) and usage == LinearUse::Consume {
12838 +
                let cellObservation = usage == LinearUse::Observe
12839 +
                    and (try inferCellPayload(checker.resolver, node)) <> nil;
12840 +
                if isMoveOnly(resultTy) and (usage == LinearUse::Consume or cellObservation) {
11544 12841
                    throw emitError(checker.resolver, node, ErrorKind::LinearPartialMove);
11545 12842
                }
11546 12843
            }
11547 12844
            try checkLinearNode(checker, env, target, LinearUse::Locate);
11548 12845
        }
11549 12846
        case ast::NodeValue::FieldAccess(access) => {
11550 12847
            if let resultTy = typeFor(checker.resolver, node) {
11551 -
                if isMoveOnly(resultTy) and usage == LinearUse::Consume {
12848 +
                let cellObservation = usage == LinearUse::Observe
12849 +
                    and (try inferCellPayload(checker.resolver, node)) <> nil;
12850 +
                if isMoveOnly(resultTy) and (usage == LinearUse::Consume or cellObservation) {
11552 12851
                    throw emitError(checker.resolver, node, ErrorKind::LinearPartialMove);
11553 12852
                }
11554 12853
            }
11555 12854
            try checkLinearNode(checker, env, access.parent, LinearUse::Locate);
11556 12855
        }
11557 12856
        case ast::NodeValue::ScopeAccess(_) => {}
11558 12857
        case ast::NodeValue::Subscript { container, index } => {
11559 12858
            if let resultTy = typeFor(checker.resolver, node) {
11560 -
                if isMoveOnly(resultTy) and usage == LinearUse::Consume {
12859 +
                let cellObservation = usage == LinearUse::Observe
12860 +
                    and (try inferCellPayload(checker.resolver, node)) <> nil;
12861 +
                if isMoveOnly(resultTy) and (usage == LinearUse::Consume or cellObservation) {
11561 12862
                    throw emitError(checker.resolver, node, ErrorKind::LinearPartialMove);
11562 12863
                }
11563 12864
            }
11564 12865
            try checkLinearNode(checker, env, container, LinearUse::Locate);
11565 12866
            try checkLinearNode(checker, env, index, LinearUse::Consume);
11784 13085
    let resolved: 'checking = &mut *self where 'arena: 'checking in {
11785 13086
        let mut checker = linearChecker(resolved, regions);
11786 13087
        let mut env = linearEnv();
11787 13088
        if let receiverNode = receiver {
11788 13089
            try addLinearBinding(&mut checker, &mut env, receiverNode);
13090 +
            if let symbol = symbolFor(checker.resolver, receiverNode) {
13091 +
                if let case SymbolData::Value {
13092 +
                    type: Type::Pointer {
13093 +
                        class: types::PointerClass::Region(permission),
13094 +
                        mutable: true,
13095 +
                        ..
13096 +
                    },
13097 +
                    ..
13098 +
                } = symbol.data {
13099 +
                    let index = checker.authorityLen;
13100 +
                    set checker.authorityPermissions[index] = permission;
13101 +
                    set checker.authorityBindings[index] = symbol;
13102 +
                    set checker.authorityExclusive[index] = true;
13103 +
                    set checker.authorityLen += 1;
13104 +
                }
13105 +
            }
11789 13106
        }
11790 13107
        for paramNode in params {
11791 13108
            let case ast::NodeValue::FnParam(_) = paramNode.value
11792 13109
                else panic "checkLinearFn: expected parameter";
11793 13110
            try addLinearBinding(&mut checker, &mut env, paramNode);
13111 +
            if let symbol = symbolFor(checker.resolver, paramNode) {
13112 +
                if let case SymbolData::Value {
13113 +
                    type: Type::Pointer {
13114 +
                        class: types::PointerClass::Region(permission),
13115 +
                        mutable: true,
13116 +
                        ..
13117 +
                    },
13118 +
                    ..
13119 +
                } = symbol.data {
13120 +
                    if checker.authorityLen >= MAX_LINEAR_BINDINGS {
13121 +
                        throw emitError(checker.resolver, paramNode, ErrorKind::Internal);
13122 +
                    }
13123 +
                    let index = checker.authorityLen;
13124 +
                    set checker.authorityPermissions[index] = permission;
13125 +
                    set checker.authorityBindings[index] = symbol;
13126 +
                    set checker.authorityExclusive[index] = true;
13127 +
                    set checker.authorityLen += 1;
13128 +
                }
13129 +
            }
11794 13130
        }
11795 13131
        try checkLinearNode(&mut checker, &mut env, body, LinearUse::Discard);
11796 13132
        try finishLinearScope(&mut checker, &mut env, 0);
11797 13133
    }
11798 13134
}
lib/std/lang/resolver/printer.rad +10 -2
107 107
            io::print("i32");
108 108
        }
109 109
        case super::Type::I64 => {
110 110
            io::print("i64");
111 111
        }
112 -
        case super::Type::Cell { class, payload } => {
112 +
        case super::Type::Cell { class, permission, payload } => {
113 113
            printPtrPrefix(class, false);
114 114
            io::print("cell ");
115 +
            if let region = permission {
116 +
                io::print(region.name);
117 +
                io::print(" ");
118 +
            }
115 119
            printTypeBody(*payload, brief);
116 120
        }
117 121
        case super::Type::Session(region) => {
118 122
            io::print("Session ");
119 123
            io::print(region.name);
618 622
        }
619 623
        case super::ErrorKind::InvalidAllocationRuntime => {
620 624
            io::print("invalid standard allocation trait signature");
621 625
        }
622 626
        case super::ErrorKind::InvalidCellPayload => {
623 -
            io::print("cell payload must be a storable plain Copy value");
627 +
            io::print("cell payload must be storable and bulk-discardable; unassociated cells also require Copy");
628 +
        }
629 +
        case super::ErrorKind::CellPermissionRequired(name) => {
630 +
            io::print("cell payload access requires matching authority for permission ");
631 +
            io::print(name);
624 632
        }
625 633
        case super::ErrorKind::InvalidSessionSource => {
626 634
            io::print("session requires one exclusive borrow of an std::lang::alloc::Alloc implementer");
627 635
        }
628 636
        case super::ErrorKind::RegionalLoanOverflow => io::print("too many simultaneous regional projections"),
lib/std/lang/resolver/tests.rad +6 -2
37 37
            super::Type::Optional(item),
38 38
            super::Type::Range { start: nil, end: nil },
39 39
            super::Type::Range { start: item, end: nil },
40 40
            super::Type::Range { start: nil, end: item },
41 41
            super::Type::Range { start: item, end: item },
42 -
            super::Type::Cell { class: types::PointerClass::Ref, payload: item },
42 +
            super::Type::Cell {
43 +
                class: types::PointerClass::Ref, permission: nil, payload: item,
44 +
            },
43 45
            super::Type::Pointer { class: types::PointerClass::Ref, target: item, mutable: false },
44 46
            super::Type::Pointer { class: types::PointerClass::Ref, target: item, mutable: true },
45 47
            super::Type::Pointer { class: types::PointerClass::Owned, target: item, mutable: false },
46 48
            super::Type::Pointer { class: types::PointerClass::Unsafe, target: item, mutable: false },
47 49
            super::Type::Slice { class: types::PointerClass::Ref, item, mutable: false },
284 286
    };
285 287
    checkFixedTypeLayout(super::Type::Fn(signature), 8, 8);
286 288
    checkFixedTypeLayout(super::Type::Session(&region), 16, 8);
287 289
    for class in [types::PointerClass::Owned, types::PointerClass::Ref,
288 290
                  types::PointerClass::Unsafe, types::PointerClass::Region(&region)] {
289 -
        checkFixedTypeLayout(super::Type::Cell { class, payload: item }, 8, 8);
291 +
        checkFixedTypeLayout(super::Type::Cell {
292 +
            class, permission: nil, payload: item,
293 +
        }, 8, 8);
290 294
        for mutable in [false, true] {
291 295
            checkFixedTypeLayout(super::Type::Pointer { class, target: item, mutable }, 8, 8);
292 296
            checkFixedTypeLayout(super::Type::Slice { class, item, mutable }, 16, 8);
293 297
            checkFixedTypeLayout(super::Type::TraitObject { class, traitInfo: &traitInfo, mutable }, 16, 8);
294 298
        }
lib/std/lang/resolver/tests/regions.rad +502 -3
1554 1554
            try super::expectNoErrors(&result);
1555 1555
        }
1556 1556
    }
1557 1557
}
1558 1558
1559 +
/// Permission-associated cells support construction, direct access, and sequential mutation.
1560 +
@test unsafe fn testPermissionCellConstruction() throws (testing::TestError) {
1561 +
    for program in [
1562 +
        // Initialized exclusive Copy storage construction.
1563 +
        "record Permit {} fn f() { let mut owner = Permit {}; let permission: 'permission = &mut owner in { let mut value: u32 = 0; let cell: &cell 'permission u32 = &cell 'permission value; set *cell = 1; let copy = *cell; } }",
1564 +
        // Sequential mutation after each previous access has ended.
1565 +
        "record Permit {} fn f 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) { set *cell = 1; let first = *cell; set *cell = first + 1; let second = *cell; }",
1566 +
    ] {
1567 +
        let mut arena = super::testArena();
1568 +
        let storage: 'test = &mut arena in {
1569 +
            let mut res = super::testResolver(storage);
1570 +
            let result = try super::resolveProgramStr(&mut res, program);
1571 +
            try super::expectNoErrors(&result);
1572 +
        }
1573 +
    }
1574 +
}
1575 +
1576 +
/// Associated cell construction requires active authority for its permission region.
1577 +
@test unsafe fn testPermissionCellConstructionAuthority() throws (testing::TestError) {
1578 +
    let mut arena = super::testArena();
1579 +
    let storage: 'test = &mut arena in {
1580 +
        let mut res = super::testResolver(storage);
1581 +
        let result = try super::resolveProgramStr(&mut res,
1582 +
            "record Permit {} fn f 'permission (place: &mut u32, owner: Permit) { let cell: &cell 'permission u32 = &cell 'permission *place; }");
1583 +
        let error = try super::expectError(&result);
1584 +
        let case resolver::ErrorKind::CellPermissionRequired(_) = error.kind
1585 +
            else throw testing::TestError::Failed;
1586 +
    }
1587 +
}
1588 +
1589 +
/// Matching authority permits shared and mutable payload loans and ordinary helper calls.
1590 +
@test unsafe fn testPermissionCellPayloadLoans() throws (testing::TestError) {
1591 +
    for program in [
1592 +
        // A shared payload reference can be passed to an ordinary helper.
1593 +
        "record Permit {} fn observe(value: &u32) {} fn f 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) { let authority: 'loan = &*permission, payload = &*cell in { observe(payload); } }",
1594 +
        // A mutable payload reference can be passed to an ordinary `&mut` helper.
1595 +
        "record Permit {} fn increment(value: &mut u32) { set *value += 1; } fn f 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) { let authority: 'loan = &mut *permission, payload = &mut *cell in { increment(payload); } }",
1596 +
        // Cell aliases retain authority and may create multiple simultaneous readers.
1597 +
        "record Permit {} fn observe(value: &u32) {} fn f 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) { let alias = cell; let authority: 'loan = &*permission, first = &*cell, second = &*alias in { observe(first); observe(second); } }",
1598 +
    ] {
1599 +
        let mut arena = super::testArena();
1600 +
        let storage: 'test = &mut arena in {
1601 +
            let mut res = super::testResolver(storage);
1602 +
            let result = try super::resolveProgramStr(&mut res, program);
1603 +
            try super::expectNoErrors(&result);
1604 +
        }
1605 +
    }
1606 +
}
1607 +
1608 +
/// Aliasing, generic substitution, and storage shortening preserve the permission association.
1609 +
@test unsafe fn testPermissionCellSubstitution() throws (testing::TestError) {
1610 +
    for program in [
1611 +
        // An inferred generic call substitutes both storage and permission regions.
1612 +
        "record Permit {} fn identity 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) -> &'storage cell 'permission u32 { return cell; } fn f 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) { let alias = cell; let instantiated = identity(alias, permission); }",
1613 +
        // Shortening storage leaves the independent permission region unchanged.
1614 +
        "record Permit {} fn shorten 'storage 'short 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) -> &'short cell 'permission u32 where 'storage: 'short { return cell; }",
1615 +
    ] {
1616 +
        let mut arena = super::testArena();
1617 +
        let storage: 'test = &mut arena in {
1618 +
            let mut res = super::testResolver(storage);
1619 +
            let result = try super::resolveProgramStr(&mut res, program);
1620 +
            try super::expectNoErrors(&result);
1621 +
        }
1622 +
    }
1623 +
}
1624 +
1625 +
/// Calls may reuse authority when a helper's permission contract does not return it.
1626 +
@test unsafe fn testPermissionCellAuthorityCallReuse() throws (testing::TestError) {
1627 +
    {
1628 +
        let mut arena = super::testArena();
1629 +
        let storage: 'test = &mut arena in {
1630 +
            let mut res = super::testResolver(storage);
1631 +
            let result = try super::resolveProgramStr(&mut res,
1632 +
                "record Permit {} fn inspect 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) -> u32 { return *cell; } fn f 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) { let first = inspect(cell, permission); let second = inspect(cell, permission); }");
1633 +
            try super::expectNoErrors(&result);
1634 +
        }
1635 +
    }
1636 +
    {
1637 +
        let mut arena = super::testArena();
1638 +
        let storage: 'test = &mut arena in {
1639 +
            let mut res = super::testResolver(storage);
1640 +
            let result = try super::resolveProgramStr(&mut res,
1641 +
                "record Permit {} fn retain 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) -> &'permission mut Permit { let value = *cell; return permission; } fn f 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) { let retained = retain(cell, permission); retain(cell, permission); }");
1642 +
            let error = try super::expectError(&result);
1643 +
            let case resolver::ErrorKind::AffineUseAfterMove(_) = error.kind
1644 +
                else throw testing::TestError::Failed;
1645 +
        }
1646 +
    }
1647 +
    {
1648 +
        let mut arena = super::testArena();
1649 +
        let storage: 'test = &mut arena in {
1650 +
            let mut res = super::testResolver(storage);
1651 +
            let result = try super::resolveProgramStr(&mut res,
1652 +
                "record Permit {} fn retainIn 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit, out: &mut ?&'permission mut Permit) { let value = *cell; set *out = permission; } fn f 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit, firstOut: &mut ?&'permission mut Permit, secondOut: &mut ?&'permission mut Permit) { retainIn(cell, permission, firstOut); retainIn(cell, permission, secondOut); }");
1653 +
            let error = try super::expectError(&result);
1654 +
            let case resolver::ErrorKind::AffineUseAfterMove(_) = error.kind
1655 +
                else throw testing::TestError::Failed;
1656 +
        }
1657 +
    }
1658 +
    {
1659 +
        let mut arena = super::testArena();
1660 +
        let storage: 'test = &mut arena in {
1661 +
            let mut res = super::testResolver(storage);
1662 +
            let result = try super::resolveProgramStr(&mut res,
1663 +
                "record Permit {} fn inspect 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) -> u32 { return *cell; } fn retainIn 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit, storage: &'permission mut ?&'permission mut Permit) { let value = *cell; set *storage = permission; } fn f 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit, authorityStorage: &'permission mut ?&'permission mut Permit) { retainIn(cell, permission, authorityStorage); inspect(cell, permission); }");
1664 +
            let error = try super::expectError(&result);
1665 +
            let case resolver::ErrorKind::AffineUseAfterMove(_) = error.kind
1666 +
                else throw testing::TestError::Failed;
1667 +
        }
1668 +
    }
1669 +
}
1670 +
1671 +
/// Fresh allocation does not reclaim storage and remains valid during a shared payload loan.
1672 +
@test unsafe fn testPermissionCellFreshAllocation() throws (testing::TestError) {
1673 +
    let mut arena = super::testArena();
1674 +
    let storage: 'test = &mut arena in {
1675 +
        let mut res = super::testResolver(storage);
1676 +
        let result = try super::resolveSessionProgramStr(&mut res,
1677 +
            "record Permit {} fn f 'storage 'permission (session: &Session 'storage, cell: &'storage cell 'permission u32, permission: &'permission mut Permit) { let authority: 'loan = &*permission, payload = &*cell in { let fresh = try! session.new(2 as u32); set *fresh = *payload; } }");
1678 +
        try super::expectNoErrors(&result);
1679 +
    }
1680 +
}
1681 +
1682 +
/// Cell permission metadata does not make a session allocation depend on shorter authority.
1683 +
@test unsafe fn testPermissionCellSessionNominalDependency() throws (testing::TestError) {
1684 +
    let mut arena = super::testArena();
1685 +
    let storage: 'test = &mut arena in {
1686 +
        let mut res = super::testResolver(storage);
1687 +
        let result = try super::resolveSessionProgramStr(&mut res,
1688 +
            "record Permit {} record Block: 'storage + 'permission + Copy { cell: &'storage cell 'permission u32 } fn f 'storage (session: &Session 'storage) { let mut owner = Permit {}; let permission: 'permission = &mut owner in { let place = try! session.new(1 as u32); let cell: &'storage cell 'permission u32 = &cell 'permission *place; let block = try! session.new(Block 'storage 'permission { cell }); } }");
1689 +
        try super::expectNoErrors(&result);
1690 +
    }
1691 +
}
1692 +
1693 +
/// Associated Copy cells can form finite-layout cycles under one permission.
1694 +
@test unsafe fn testPermissionCellCycles() throws (testing::TestError) {
1695 +
    let mut arena = super::testArena();
1696 +
    let storage: 'test = &mut arena in {
1697 +
        let mut res = super::testResolver(storage);
1698 +
        let result = try super::resolveProgramStr(&mut res,
1699 +
            "record Left: 'storage + 'permission + Copy { right: &'storage cell 'permission Right 'storage 'permission } record Right: 'storage + 'permission + Copy { left: &'storage cell 'permission Left 'storage 'permission }");
1700 +
        try super::expectNoErrors(&result);
1701 +
    }
1702 +
}
1703 +
1704 +
/// Owned cell payloads ignore nested permission-only metadata but retain storage dependencies.
1705 +
@test unsafe fn testPermissionCellOwnedNestedPayloadRegions() throws (testing::TestError) {
1706 +
    {
1707 +
        let mut arena = super::testArena();
1708 +
        let storage: 'test = &mut arena in {
1709 +
            let mut res = super::testResolver(storage);
1710 +
            let result = try super::resolveProgramStr(&mut res,
1711 +
                "record Permit {} record Payload: 'permission + Copy { nested: *cell 'permission u32 } fn f 'permission (place: *mut Payload 'permission, permission: &'permission mut Permit) -> *cell Payload 'permission { return &cell *place; }");
1712 +
            try super::expectNoErrors(&result);
1713 +
        }
1714 +
    }
1715 +
    {
1716 +
        let mut arena = super::testArena();
1717 +
        let storage: 'test = &mut arena in {
1718 +
            let mut res = super::testResolver(storage);
1719 +
            let result = try super::resolveProgramStr(&mut res,
1720 +
                "record Payload: 'storage + Copy { nested: &'storage cell u32 } fn f 'storage (place: *mut Payload 'storage) -> *cell Payload 'storage { return &cell *place; }");
1721 +
            try super::expectErrorKind(&result, resolver::ErrorKind::InvalidCellPayload);
1722 +
        }
1723 +
    }
1724 +
}
1725 +
1726 +
/// Resolved cell metadata keeps storage and permission identities distinct through substitution.
1727 +
@test unsafe fn testPermissionCellTypeMetadata() throws (testing::TestError) {
1728 +
    let mut arena = super::testArena();
1729 +
    let storage: 'test = &mut arena in {
1730 +
        let mut res = super::testResolver(storage);
1731 +
        let result = try super::resolveProgramStr(&mut res,
1732 +
            "record Permit {} fn identity 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) -> &'storage cell 'permission u32 { return cell; } fn inspect 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) { let alias = cell; let instantiated = identity(alias, permission); }");
1733 +
        try super::expectNoErrors(&result);
1734 +
1735 +
        let inspect = try super::getBlockStmt(result.root, 2);
1736 +
        let inspectType = resolver::typeFor(&res, inspect) else throw testing::TestError::Failed;
1737 +
        let case resolver::Type::Fn(info) = inspectType else throw testing::TestError::Failed;
1738 +
        let case resolver::Type::Cell {
1739 +
            class: types::PointerClass::Region(storageRegion),
1740 +
            permission: declaredPermission,
1741 +
            payload: declaredPayload,
1742 +
        } = *info.paramTypes[0] else throw testing::TestError::Failed;
1743 +
        let permissionRegion = declaredPermission else throw testing::TestError::Failed;
1744 +
        let case resolver::Type::Pointer {
1745 +
            class: types::PointerClass::Region(authorityRegion),
1746 +
            target: _,
1747 +
            mutable: true,
1748 +
        } = *info.paramTypes[1] else throw testing::TestError::Failed;
1749 +
        try testing::expect(storageRegion.id <> permissionRegion.id);
1750 +
        try testing::expect(authorityRegion.id == permissionRegion.id);
1751 +
        try testing::expect(*declaredPayload == resolver::Type::U32);
1752 +
1753 +
        let case ast::NodeValue::FnDecl(decl) = inspect.value else throw testing::TestError::Failed;
1754 +
        let body = decl.body else throw testing::TestError::Failed;
1755 +
        let case ast::NodeValue::Let(aliasDecl) =
1756 +
            (try super::getBlockStmt(body, 0)).value else throw testing::TestError::Failed;
1757 +
        let case ast::NodeValue::Let(instantiatedDecl) =
1758 +
            (try super::getBlockStmt(body, 1)).value else throw testing::TestError::Failed;
1759 +
        let aliasType = resolver::typeFor(&res, aliasDecl.value) else throw testing::TestError::Failed;
1760 +
        let instantiatedType = resolver::typeFor(&res, instantiatedDecl.value)
1761 +
            else throw testing::TestError::Failed;
1762 +
        let case resolver::Type::Cell {
1763 +
            class: types::PointerClass::Region(aliasStorage),
1764 +
            permission: aliasPermission,
1765 +
            ..
1766 +
        } = aliasType else throw testing::TestError::Failed;
1767 +
        let case resolver::Type::Cell {
1768 +
            class: types::PointerClass::Region(instantiatedStorage),
1769 +
            permission: instantiatedPermission,
1770 +
            ..
1771 +
        } = instantiatedType else throw testing::TestError::Failed;
1772 +
        let aliasPermissionRegion = aliasPermission else throw testing::TestError::Failed;
1773 +
        let instantiatedPermissionRegion = instantiatedPermission else throw testing::TestError::Failed;
1774 +
        try testing::expect(aliasStorage.id == storageRegion.id);
1775 +
        try testing::expect(instantiatedStorage.id == storageRegion.id);
1776 +
        try testing::expect(aliasPermissionRegion.id == permissionRegion.id);
1777 +
        try testing::expect(instantiatedPermissionRegion.id == permissionRegion.id);
1778 +
    }
1779 +
}
1780 +
1781 +
/// Permission-wide loans reject conflicting accesses through every cell alias.
1782 +
@test unsafe fn testPermissionCellAliasConflicts() throws (testing::TestError) {
1783 +
    for program in [
1784 +
        // Two aliases cannot produce overlapping mutable payload references.
1785 +
        "record Permit {} fn f 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) { let alias = cell; let authority: 'loan = &mut *permission, first = &mut *cell, second = &mut *alias in {} }",
1786 +
        // A shared payload loan suspends mutation through another alias.
1787 +
        "record Permit {} fn f 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) { let alias = cell; let authority: 'loan = &*permission, payload = &*cell in { set *alias = 1; let value = *payload; } }",
1788 +
    ] {
1789 +
        let mut arena = super::testArena();
1790 +
        let storage: 'test = &mut arena in {
1791 +
            let mut res = super::testResolver(storage);
1792 +
            let result = try super::resolveProgramStr(&mut res, program);
1793 +
            let error = try super::expectError(&result);
1794 +
            let case resolver::ErrorKind::BorrowConflict(_) = error.kind
1795 +
                else throw testing::TestError::Failed;
1796 +
        }
1797 +
    }
1798 +
}
1799 +
/// Call argument loans preserve permission identity across distinct cell handles.
1800 +
@test unsafe fn testPermissionCellCallArgumentAliasConflict() throws (testing::TestError) {
1801 +
    let mut arena = super::testArena();
1802 +
    let storage: 'test = &mut arena in {
1803 +
        let mut res = super::testResolver(storage);
1804 +
        let result = try super::resolveProgramStr(&mut res,
1805 +
            "record Permit {} fn both(first: &u32, second: &mut u32) {} fn f 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) { let alias = cell; let authority: 'loan = &mut *permission where 'permission: 'loan in { both(&*cell, &mut *alias); } }");
1806 +
        try super::expectErrorKind(&result, resolver::ErrorKind::BorrowConflict("alias"));
1807 +
    }
1808 +
}
1809 +
1810 +
/// Wrapped local payload loans preserve permission identity.
1811 +
@test unsafe fn testPermissionCellWrappedLocalLoanConflict() throws (testing::TestError) {
1812 +
    let mut arena = super::testArena();
1813 +
    let storage: 'test = &mut arena in {
1814 +
        let mut res = super::testResolver(storage);
1815 +
        let result = try super::resolveProgramStr(&mut res,
1816 +
            "record Permit {} fn f 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) { let alias = cell; let authority: 'loan = &*permission where 'permission: 'loan in { let payload = &*cell as &u32; set *alias = 1; let value = *payload; } }");
1817 +
        let error = try super::expectError(&result);
1818 +
        let case resolver::ErrorKind::BorrowConflict(_) = error.kind
1819 +
            else throw testing::TestError::Failed;
1820 +
    }
1821 +
}
1822 +
/// Sessions nested in cell payloads retain consumed permission authority.
1823 +
@test unsafe fn testPermissionCellNestedSessionRetention() throws (testing::TestError) {
1824 +
    let mut arena = super::testArena();
1825 +
    let storage: 'test = &mut arena in {
1826 +
        let mut res = super::testResolver(storage);
1827 +
        let result = try super::resolveSessionProgramStr(&mut res,
1828 +
            "record Permit {} fn retain 'storage 'session 'permission (holder: &'storage cell 'permission &'session mut Session 'permission, permission: &'permission mut Permit) { let stored = try! (*holder).new(permission); } fn f 'storage 'session 'permission (holder: &'storage cell 'permission &'session mut Session 'permission, permission: &'permission mut Permit) { retain(holder, permission); retain(holder, permission); }");
1829 +
        try super::expectErrorKind(
1830 +
            &result, resolver::ErrorKind::AffineUseAfterMove("permission"),
1831 +
        );
1832 +
    }
1833 +
}
1834 +
1835 +
1836 +
/// Associated cell projections support replacement under matching authority.
1837 +
@test unsafe fn testPermissionCellProjectedReplacement() throws (testing::TestError) {
1838 +
    for program in [
1839 +
        "record Permit {} record Payload { value: u32 } fn f 'storage 'permission (cell: &'storage cell 'permission Payload, permission: &'permission mut Permit) { set (*cell).value = 1; }",
1840 +
        "record Permit {} fn f 'storage 'permission (cell: &'storage cell 'permission [u32; 2], permission: &'permission mut Permit) { set (*cell)[0] = 1; }",
1841 +
        "record Permit {} fn f 'storage 'permission (cell: &'storage cell 'permission [u32; 2], permission: &'permission mut Permit) { set (*cell)[0..1] = 0; }",
1842 +
    ] {
1843 +
        let mut arena = super::testArena();
1844 +
        let storage: 'test = &mut arena in {
1845 +
            let mut res = super::testResolver(storage);
1846 +
            let result = try super::resolveProgramStr(&mut res, program);
1847 +
            try super::expectNoErrors(&result);
1848 +
        }
1849 +
    }
1850 +
}
1851 +
1852 +
1853 +
/// Permission identities are invariant across access, relabeling, and storage shortening.
1854 +
@test unsafe fn testPermissionCellAssociationMismatch() throws (testing::TestError) {
1855 +
    {
1856 +
        let mut arena = super::testArena();
1857 +
        let storage: 'test = &mut arena in {
1858 +
            let mut res = super::testResolver(storage);
1859 +
            // Cross-permission access fails generic region inference.
1860 +
            let result = try super::resolveProgramStr(&mut res,
1861 +
                "record Permit {} fn access 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) -> u32 { return *cell; } fn cross 'storage 'first 'second (cell: &'storage cell 'first u32, first: &'first mut Permit, second: &'second mut Permit) { access(cell, second); }");
1862 +
            let error = try super::expectError(&result);
1863 +
            let case resolver::ErrorKind::RegionInference(_) = error.kind
1864 +
                else throw testing::TestError::Failed;
1865 +
        }
1866 +
    }
1867 +
    for program in [
1868 +
        // An explicit annotation cannot relabel a permission.
1869 +
        "record Permit {} fn f 'storage 'first 'second (cell: &'storage cell 'first u32, first: &'first mut Permit, second: &'second mut Permit) { let relabeled: &'storage cell 'second u32 = cell; }",
1870 +
        // Storage shortening cannot change the permission association.
1871 +
        "record Permit {} fn f 'storage 'short 'first 'second (cell: &'storage cell 'first u32, first: &'first mut Permit, second: &'second mut Permit) where 'storage: 'short { let relabeled: &'short cell 'second u32 = cell; }",
1872 +
        // Storage shortening cannot drop the permission association.
1873 +
        "record Permit {} fn f 'storage 'short 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) where 'storage: 'short { let unassociated: &'short cell u32 = cell; }",
1874 +
    ] {
1875 +
        let mut arena = super::testArena();
1876 +
        let storage: 'test = &mut arena in {
1877 +
            let mut res = super::testResolver(storage);
1878 +
            let result = try super::resolveProgramStr(&mut res, program);
1879 +
            let error = try super::expectError(&result);
1880 +
            let case resolver::ErrorKind::TypeMismatch(_) = error.kind
1881 +
                else throw testing::TestError::Failed;
1882 +
        }
1883 +
    }
1884 +
}
1885 +
1886 +
/// Distinct formal permissions cannot substitute the same actual permission identity.
1887 +
@test unsafe fn testPermissionCellDistinctGenericArguments() throws (testing::TestError) {
1888 +
    let mut arena = super::testArena();
1889 +
    let storage: 'test = &mut arena in {
1890 +
        let mut res = super::testResolver(storage);
1891 +
        let result = try super::resolveProgramStr(&mut res,
1892 +
            "record Permit {} fn separate 'storage 'left 'right (first: &'storage cell 'left u32, left: &'left mut Permit, second: &'storage cell 'right u32, right: &'right mut Permit) {} fn f 'storage 'permission (first: &'storage cell 'permission u32, second: &'storage cell 'permission u32, permission: &'permission mut Permit) { separate 'storage 'permission 'permission(first, permission, second, permission); }");
1893 +
        let error = try super::expectError(&result);
1894 +
        let case resolver::ErrorKind::RegionInference(_) = error.kind
1895 +
            else throw testing::TestError::Failed;
1896 +
    }
1897 +
}
1898 +
1899 +
/// Applied nominal fields preserve distinct formal permission identities at calls.
1900 +
@test unsafe fn testPermissionCellNominalGenericArguments() throws (testing::TestError) {
1901 +
    {
1902 +
        let mut arena = super::testArena();
1903 +
        let storage: 'test = &mut arena in {
1904 +
            let mut res = super::testResolver(storage);
1905 +
            let result = try super::resolveProgramStr(&mut res,
1906 +
                "record Permit {} record Wrapper: 'storage + 'permission + Copy { cell: &'storage cell 'permission u32 } fn separate 'storage 'left 'right (first: Wrapper 'storage 'left, left: &'left mut Permit, second: Wrapper 'storage 'right, right: &'right mut Permit) {} fn f 'storage 'left 'right (first: Wrapper 'storage 'left, left: &'left mut Permit, second: Wrapper 'storage 'right, right: &'right mut Permit) { separate(first, left, second, right); }");
1907 +
            try super::expectNoErrors(&result);
1908 +
        }
1909 +
    }
1910 +
    {
1911 +
        let mut arena = super::testArena();
1912 +
        let storage: 'test = &mut arena in {
1913 +
            let mut res = super::testResolver(storage);
1914 +
            let result = try super::resolveProgramStr(&mut res,
1915 +
                "record Permit {} record Wrapper: 'storage + 'permission + Copy { cell: &'storage cell 'permission u32 } fn separate 'storage 'left 'right (first: Wrapper 'storage 'left, left: &'left mut Permit, second: Wrapper 'storage 'right, right: &'right mut Permit) {} fn f 'storage 'permission (first: Wrapper 'storage 'permission, second: Wrapper 'storage 'permission, permission: &'permission mut Permit) { separate(first, permission, second, permission); }");
1916 +
            let error = try super::expectError(&result);
1917 +
            let case resolver::ErrorKind::RegionInference(_) = error.kind
1918 +
                else throw testing::TestError::Failed;
1919 +
        }
1920 +
    }
1921 +
}
1922 +
1923 +
/// Direct and callback cell accesses cannot conflict with a live payload loan.
1924 +
@test unsafe fn testPermissionCellCallConflicts() throws (testing::TestError) {
1925 +
    for program in [
1926 +
        // Direct call.
1927 +
        "record Permit {} fn mutate 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) { set *cell = 1; } fn f 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) { let authority: 'loan = &*permission, payload = &*cell in { mutate(cell, permission); let value = *payload; } }",
1928 +
        // Region-instantiated callback.
1929 +
        "record Permit {} fn mutate 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) { set *cell = 1; } fn f 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) { let callback = mutate 'storage 'permission; let authority: 'loan = &*permission, payload = &*cell in { callback(cell, permission); let value = *payload; } }",
1930 +
    ] {
1931 +
        let mut arena = super::testArena();
1932 +
        let storage: 'test = &mut arena in {
1933 +
            let mut res = super::testResolver(storage);
1934 +
            let result = try super::resolveProgramStr(&mut res, program);
1935 +
            let error = try super::expectError(&result);
1936 +
            let case resolver::ErrorKind::BorrowConflict(_) = error.kind
1937 +
                else throw testing::TestError::Failed;
1938 +
        }
1939 +
    }
1940 +
}
1941 +
1942 +
/// Payload references cannot escape their matching permission loan.
1943 +
@test unsafe fn testPermissionCellLoanEscape() throws (testing::TestError) {
1944 +
    let mut arena = super::testArena();
1945 +
    let storage: 'test = &mut arena in {
1946 +
        let mut res = super::testResolver(storage);
1947 +
        let result = try super::resolveProgramStr(&mut res,
1948 +
            "record Permit {} fn escape 'storage 'permission (cell: &'storage cell 'permission u32, permission: &'permission mut Permit) -> &'storage u32 { let authority: 'loan = &*permission, payload = &*cell in { return payload; } }");
1949 +
        let error = try super::expectError(&result);
1950 +
        let case resolver::ErrorKind::RegionEscape(_) = error.kind
1951 +
            else throw testing::TestError::Failed;
1952 +
    }
1953 +
}
1954 +
1955 +
/// Allocation-session escape and reset remain invalid while an associated payload reference is live.
1956 +
@test unsafe fn testPermissionCellStorageLiveness() throws (testing::TestError) {
1957 +
    {
1958 +
        let mut arena = super::testArena();
1959 +
        let storage: 'test = &mut arena in {
1960 +
            let mut res = super::testResolver(storage);
1961 +
            // A payload reference cannot escape the allocation session that owns its cell storage.
1962 +
            let result = try super::resolveSessionProgramStr(&mut res,
1963 +
                "use std::lang::alloc; record Permit {} fn escape 'arena (arena: &'arena mut alloc::Arena) -> &'arena u32 { let mut owner = Permit {}; let permission: 'permission = &mut owner in { use *arena as session in { let place = try! session.new(1 as u32); let cell = &cell 'permission *place; let authority: 'loan = &*permission, payload = &*cell in { return payload; } } } }");
1964 +
            let error = try super::expectError(&result);
1965 +
            let case resolver::ErrorKind::RegionEscape(_) = error.kind
1966 +
                else throw testing::TestError::Failed;
1967 +
        }
1968 +
    }
1969 +
    {
1970 +
        let mut arena = super::testArena();
1971 +
        let storage: 'test = &mut arena in {
1972 +
            let mut res = super::testResolver(storage);
1973 +
            // Reset cannot reclaim a cell's storage while its payload reference is live.
1974 +
            let result = try super::resolveSessionProgramStr(&mut res,
1975 +
                "use std::lang::alloc; record Permit {} fn reset 'storage 'permission (arena: &'storage mut alloc::Arena, cell: &'storage cell 'permission u32, permission: &'permission mut Permit) { let authority: 'loan = &*permission, payload = &*cell in { alloc::reset(arena); let value = *payload; } }");
1976 +
            let error = try super::expectError(&result);
1977 +
            let case resolver::ErrorKind::BorrowConflict(_) = error.kind
1978 +
                else throw testing::TestError::Failed;
1979 +
        }
1980 +
    }
1981 +
}
1982 +
1983 +
/// Permission-associated cells admit affine values that are safe for bulk reclamation.
1984 +
@test unsafe fn testPermissionCellAffinePayload() throws (testing::TestError) {
1985 +
    for program in [
1986 +
        // Construction accepts an affine, bulk-discardable record.
1987 +
        "record Permit {} record Payload { value: u32 } fn f 'permission (place: &mut Payload, permission: &'permission mut Permit) { let cell: &cell 'permission Payload = &cell 'permission *place; }",
1988 +
        // Matching shared authority permits an ordinary shared payload loan.
1989 +
        "record Permit {} record Payload { value: u32 } fn observe(value: &Payload) {} fn f 'storage 'permission (cell: &'storage cell 'permission Payload, permission: &'permission mut Permit) { let authority: 'loan = &*permission, payload = &*cell in { observe(payload); } }",
1990 +
        // Matching mutable authority permits an ordinary mutable helper call.
1991 +
        "record Permit {} record Payload { value: u32 } fn increment(value: &mut Payload) { set value.value += 1; } fn f 'storage 'permission (cell: &'storage cell 'permission Payload, permission: &'permission mut Permit) { let authority: 'loan = &mut *permission, payload = &mut *cell in { increment(payload); } }",
1992 +
        // Replacement evaluates the new value from the old payload before overwriting it.
1993 +
        "record Permit {} record Payload { value: u32 } fn replacement(value: &Payload) -> Payload { return Payload { value: value.value + 1 }; } fn f 'storage 'permission (cell: &'storage cell 'permission Payload, permission: &'permission mut Permit) { set *cell = replacement(&*cell); }",
1994 +
    ] {
1995 +
        let mut arena = super::testArena();
1996 +
        let storage: 'test = &mut arena in {
1997 +
            let mut res = super::testResolver(storage);
1998 +
            let result = try super::resolveProgramStr(&mut res, program);
1999 +
            try super::expectNoErrors(&result);
2000 +
        }
2001 +
    }
2002 +
}
2003 +
2004 +
/// Cell payload eligibility remains narrow without a bulk-discardable permission association.
2005 +
@test unsafe fn testPermissionCellAffinePayloadEligibility() throws (testing::TestError) {
2006 +
    for program in [
2007 +
        // An unassociated cell still requires a Copy payload.
2008 +
        "record Payload { value: u32 } fn f(place: &mut Payload) { let cell = &cell *place; }",
2009 +
        // A linear payload cannot be discarded by replacement or arena reclamation.
2010 +
        "record Permit {} record Payload: Once { value: u32 } fn f 'permission (place: &mut Payload, permission: &'permission mut Permit) { let cell: &cell 'permission Payload = &cell 'permission *place; }",
2011 +
    ] {
2012 +
        let mut arena = super::testArena();
2013 +
        let storage: 'test = &mut arena in {
2014 +
            let mut res = super::testResolver(storage);
2015 +
            let result = try super::resolveProgramStr(&mut res, program);
2016 +
            try super::expectErrorKind(&result, resolver::ErrorKind::InvalidCellPayload);
2017 +
        }
2018 +
    }
2019 +
}
2020 +
2021 +
/// Affine associated payloads can only be accessed through explicit borrows or replacement.
2022 +
@test unsafe fn testPermissionCellAffinePayloadMoves() throws (testing::TestError) {
2023 +
    for program in [
2024 +
        // A value-context dereference cannot move the whole payload out of shared storage.
2025 +
        "record Permit {} record Payload { value: u32 } fn f 'storage 'permission (cell: &'storage cell 'permission Payload, permission: &'permission mut Permit) { let moved = *cell; }",
2026 +
        // A shared payload loan cannot move an affine field out of the stored value.
2027 +
        "record Permit {} record Item { value: u32 } record Payload { item: Item } fn f 'storage 'permission (cell: &'storage cell 'permission Payload, permission: &'permission mut Permit) { let authority: 'loan = &*permission, payload = &*cell in { let moved = payload.item; } }",
2028 +
    ] {
2029 +
        let mut arena = super::testArena();
2030 +
        let storage: 'test = &mut arena in {
2031 +
            let mut res = super::testResolver(storage);
2032 +
            let result = try super::resolveProgramStr(&mut res, program);
2033 +
            try super::expectErrorKind(&result, resolver::ErrorKind::LinearPartialMove);
2034 +
        }
2035 +
    }
2036 +
}
2037 +
2038 +
/// Observing an affine payload value still requires an explicit shared reference.
2039 +
@test unsafe fn testPermissionCellAffinePayloadObserve() throws (testing::TestError) {
2040 +
    {
2041 +
        let mut arena = super::testArena();
2042 +
        let storage: 'test = &mut arena in {
2043 +
            let mut res = super::testResolver(storage);
2044 +
            let result = try super::resolveProgramStr(&mut res,
2045 +
                "record Permit {} record Payload { value: u32 } fn f 'storage 'permission (cell: &'storage cell 'permission Payload, permission: &'permission mut Permit) { let equal = *cell == *cell; }");
2046 +
            try super::expectErrorKind(&result, resolver::ErrorKind::LinearPartialMove);
2047 +
        }
2048 +
    }
2049 +
    {
2050 +
        let mut arena = super::testArena();
2051 +
        let storage: 'test = &mut arena in {
2052 +
            let mut res = super::testResolver(storage);
2053 +
            let result = try super::resolveProgramStr(&mut res,
2054 +
                "record Permit {} record Payload { value: u32 } fn f 'storage 'permission (cell: &'storage cell 'permission Payload, permission: &'permission mut Permit) { let authority: 'loan = &*permission, left = &*cell, right = &*cell in { let sameReference = left == right; let sameValue = left.value == right.value; } }");
2055 +
            try super::expectNoErrors(&result);
2056 +
        }
2057 +
    }
2058 +
}
2059 +
1559 2060
/// Cell creation requires exclusive access for the full borrow duration.
1560 2061
@test unsafe fn testCellBorrowConflicts() throws (testing::TestError) {
1561 2062
    for program in [
1562 2063
        "fn f() { let mut n: u32 = 0; let c = &cell n; let r = &n; }",
1563 2064
        "unsafe fn f() { let mut n: u32 = 0; let c = &cell n; let r = &n; }",
1576 2077
            let case resolver::ErrorKind::BorrowConflict(_) = error.kind else throw testing::TestError::Failed;
1577 2078
        }
1578 2079
    }
1579 2080
}
1580 2081
1581 -
/// Cell creation rejects immutable places and non-Copy payloads.
2082 +
/// Cell creation requires an exclusive initialized place.
1582 2083
@test unsafe fn testCellBorrowPayload() throws (testing::TestError) {
1583 2084
    for program in [
1584 2085
        "fn f() { let n: u32 = 0; let c = &cell n; }",
1585 2086
        "fn f(p: &u32) { let c = &cell *p; }",
1586 2087
        "unsafe fn f(p: &u32) { let c = &cell *p; }",
1611 2112
    for program in [
1612 2113
        "fn f(p: *cell u32) { let r = &*p; }",
1613 2114
        "unsafe fn f(p: *cell u32) { let r = &*p; }",
1614 2115
        "record R: Copy { n: u32 } fn f(p: *cell R) { let r = &(*p).n; }",
1615 2116
        "fn f(p: *cell [u32; 2]) { let r = &(*p)[0]; }",
1616 -
        "record R: Copy { n: u32 } fn f(p: *cell R) { set (*p).n = 1; }",
1617 -
        "fn f(p: *cell [u32; 2]) { set (*p)[0] = 1; }",
1618 2117
    ] {
1619 2118
        let mut testArena57 = super::testArena();
1620 2119
        let testStorage57: 'test57 = &mut testArena57 in {
1621 2120
            let mut res = super::testResolver(testStorage57);
1622 2121
            let result = try super::resolveProgramStr(&mut res, program);
seed/radiance.rv64 +0 -0

Binary file changed.

seed/radiance.rv64.git +1 -1
1 -
55199dd625f01384eae1694dba6d6c286292a12c466e40b968e8326bdf78f33e
1 +
80a2b616ded7c68d39a1ce07f86b6b059c03a32a26ae83307ae050b4b8074f90
test/tests/regions.cell.permission.cycle.rad added +109 -0
1 +
//! returns: 42
2 +
//! session-support
3 +
//! Exercise a permission-associated cell cycle backed by session storage.
4 +
5 +
use std::lang::alloc;
6 +
7 +
/// Element count whose byte size exceeds the allocator's 32-bit layout range.
8 +
constant OVERFLOW_COUNT: u32 = 4294967295;
9 +
10 +
/// Affine owner of the authority required to access associated cells.
11 +
record Permit {}
12 +
13 +
/// Affine, bulk-discardable graph payload.
14 +
record Node: 'storage + 'permission {
15 +
    /// Value contributed while traversing the cycle.
16 +
    value: u32,
17 +
    /// Optional link to another node under the same authority.
18 +
    next: ?&'storage cell 'permission Node 'storage 'permission,
19 +
}
20 +
21 +
/// Mutate an ordinary exclusive payload reference without cell knowledge.
22 +
fn increment 'storage 'permission (node: &mut Node 'storage 'permission) {
23 +
    set node.value += 1;
24 +
}
25 +
26 +
/// Verify both links and values through ordinary shared payload references.
27 +
fn inspectCycle 'storage 'permission (
28 +
    firstNode: &Node 'storage 'permission,
29 +
    secondNode: &Node 'storage 'permission,
30 +
    first: &'storage cell 'permission Node 'storage 'permission,
31 +
    second: &'storage cell 'permission Node 'storage 'permission,
32 +
) -> u32 {
33 +
    let firstNext = firstNode.next else panic "inspectCycle: missing second node";
34 +
    let secondNext = secondNode.next else panic "inspectCycle: missing cycle edge";
35 +
    assert firstNode.value == 20;
36 +
    assert secondNode.value == 22;
37 +
    assert firstNext == second;
38 +
    assert secondNext == first;
39 +
    return firstNode.value + secondNode.value;
40 +
}
41 +
42 +
/// Attempt an allocation that must fail before producing a replacement payload.
43 +
fn failingReplacement 'storage 'permission (
44 +
    storage: &Session 'storage,
45 +
    next: &'storage cell 'permission Node 'storage 'permission,
46 +
) -> Node 'storage 'permission throws (alloc::AllocError)
47 +
    where 'permission: 'storage
48 +
{
49 +
    let reservation = try storage.fill(0 as u64, OVERFLOW_COUNT);
50 +
    assert reservation.len == OVERFLOW_COUNT;
51 +
    return Node 'storage 'permission { value: 99, next };
52 +
}
53 +
54 +
/// Fallibly allocate, associate, initialize, and exercise a two-node cycle.
55 +
fn exerciseCycle 'storage 'permission (
56 +
    storage: &Session 'storage,
57 +
    permission: &'permission mut Permit,
58 +
) -> u32 throws (alloc::AllocError) where 'permission: 'storage {
59 +
    let firstPlace = try storage.new(
60 +
        Node 'storage 'permission { value: 19, next: nil }
61 +
    );
62 +
    let secondPlace = try storage.new(
63 +
        Node 'storage 'permission { value: 22, next: nil }
64 +
    );
65 +
    let first: &'storage cell 'permission Node 'storage 'permission =
66 +
        &cell 'permission *firstPlace;
67 +
    let second: &'storage cell 'permission Node 'storage 'permission =
68 +
        &cell 'permission *secondPlace;
69 +
    set *first = Node 'storage 'permission { value: 19, next: second };
70 +
    set *second = Node 'storage 'permission { value: 22, next: first };
71 +
    let authority: 'mutation = &mut *permission, payload = &mut *first in {
72 +
        increment(payload);
73 +
    }
74 +
75 +
    set *first = try failingReplacement(storage, first)
76 +
        catch error as alloc::AllocError
77 +
    {
78 +
        assert error == alloc::AllocError::OutOfMemory;
79 +
        let authority: 'observation = &*permission,
80 +
            firstPayload = &*first, secondPayload = &*second
81 +
        in {
82 +
            return inspectCycle(firstPayload, secondPayload, first, second);
83 +
        }
84 +
    };
85 +
    panic "exerciseCycle: failing replacement succeeded";
86 +
}
87 +
88 +
/// Exercise cyclic mutation, traversal, failure atomicity, and reclamation.
89 +
@default fn main() -> u32 {
90 +
    static DATA: [u8; 1024] = [0; 1024];
91 +
    let mut arena = alloc::new(&mut DATA[..]);
92 +
    let mut result: u32 = 0;
93 +
    {
94 +
        let mut owner = Permit {};
95 +
        let permission: 'permission = &mut owner in {
96 +
            use arena as storage in {
97 +
                assert @sizeOf(&'storage cell 'permission Node 'storage 'permission)
98 +
                    == @sizeOf(&'storage cell u32);
99 +
                set result = try exerciseCycle(&storage, permission) catch {
100 +
                    panic "main: cycle allocation failed";
101 +
                };
102 +
            }
103 +
        }
104 +
    }
105 +
    assert alloc::used(&arena) > 0;
106 +
    alloc::reset(&mut arena);
107 +
    assert alloc::used(&arena) == 0;
108 +
    return result;
109 +
}