aboutsummaryrefslogtreecommitdiff
path: root/tests/programs/borrow_rules.zc
blob: ed2b1998a8981a427e42a3a33f892b49c000824c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
namespace;
include rt;

// last-use borrows do not block an owner's later move; disjoint projections remain independently usable.
struct pair { int left, right; };
int*.u make(int n) { int* p = rt.new(int); *p = n; return p; }
int take(int*.d p) { return p[0]; }
int twice(int*.m p, int*.m q) { return p[0] + q[0]; }
char* alias(char*.m p) { return p; }
word.u counter() {
 int n = 0;
 let next = fn() { n++; return n; };
 return next;
}
word.u object_counter() {
 int* value = rt.new(int);
 let next = fn() { value[0]++; return value[0]; };
 return next;
}
fn main() {
 let p = make(7); int* borrowed = p + 0;
 rt.put_n(borrowed[0]); rt.put_c(32); rt.put_n(twice(p,p)); rt.put_c(32);
 rt.put_n(take(p)); rt.put_c(32);
 let disposable = rt.new(2); rt.free(disposable);
 pair* item = rt.new(pair); int* left = &item.left; int* right = &item.right;
 *left = 3; *right = 4; rt.put_n(*left + *right); rt.put_c(32);
 int[3] a = {1,2,3}; int* middle = &a[1]; middle[-1] = 5; a[2] = 6;
 rt.put_n(middle[-1] + middle[1]); rt.put_c(32);
 int[?] values = {8,9}; int* first = &values[0]; rt.put_n(first[0]); rt.put_c(32); resize(values,3);
 rt.put_n(len(values)); rt.put_c(32);
 int n = 0; let next = fn() { return ++n; }; let current = fn() { return n; };
 next(); n = 10; rt.put_n(current()); rt.put_c(32); rt.put_n(next()); rt.put_c(32); rt.put_n(n); rt.put_c(32);
 let escaping = counter(); rt.gc(); rt.put_n(escaping()); rt.put_c(32); rt.put_n(escaping()); rt.put_c(32);
 let heap = object_counter(); rt.gc(); rt.put_n(heap()); rt.put_c(32); rt.put_n(heap()); rt.put_c(32);
 int sum = 0, i = 0; while (i < 3) { sum += i; let f = fn() { return ++sum; }; f(); i++; }
 rt.put_n(sum); rt.put_c(32);
 let raw = fn() { return asm { n @ }; }; rt.put_n(raw()); rt.put_c(32);
 rt.put_s(alias("ok")); rt.put_c(10);
}