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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
use crate::abstract_state::Mutability;
use std::collections::HashMap;
type PartitionID = u16;
type Nonce = (u16, Mutability);
type NonceSet = Vec<Nonce>;
type Path = Vec<u8>;
type Edge = (PartitionID, PartitionID, Path, EdgeType);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EdgeType {
Weak,
Strong,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BorrowGraph {
partitions: Vec<PartitionID>,
partition_map: HashMap<PartitionID, NonceSet>,
edges: Vec<Edge>,
partition_counter: u16,
}
impl BorrowGraph {
pub fn new(num_locals: u8) -> BorrowGraph {
BorrowGraph {
partitions: Vec::with_capacity(num_locals as usize),
partition_map: HashMap::new(),
edges: Vec::new(),
partition_counter: u16::from(num_locals),
}
}
pub fn fresh_partition(&mut self, n: Nonce) -> Result<(), String> {
if self.partition_counter.checked_add(1).is_some() {
if self.partition_map.get(&self.partition_counter).is_some() {
return Err("Partition map already contains ID".to_string());
}
self.partition_map.insert(self.partition_counter, vec![n]);
assume!(self.partitions.len() < usize::max_value());
self.partitions.push(self.partition_counter);
Ok(())
} else {
Err("Partition map is full".to_string())
}
}
pub fn partition_mutability(&self, partition_id: PartitionID) -> Result<Mutability, String> {
if let Some(nonce_set) = self.partition_map.get(&partition_id) {
if nonce_set
.iter()
.all(|(_, mutability)| *mutability == Mutability::Mutable)
{
Ok(Mutability::Mutable)
} else if nonce_set
.iter()
.all(|(_, mutability)| *mutability == Mutability::Immutable)
{
Ok(Mutability::Immutable)
} else {
Ok(Mutability::Either)
}
} else {
Err("Partition map does not contain given partition ID".to_string())
}
}
pub fn partition_freezable(&self, partition_id: PartitionID) -> Result<bool, String> {
let mut freezable = true;
if self.partition_map.get(&partition_id).is_some() {
for (p1, p2, _, _) in self.edges.iter() {
if *p1 == partition_id && self.partition_mutability(*p2)? == Mutability::Mutable {
freezable = false;
}
}
Ok(freezable)
} else {
Err("Partition map does not contain given partition ID".to_string())
}
}
fn path_is_prefix(&self, path_1: Path, path_2: Path) -> bool {
let mut prefix = true;
for (i, field) in path_1.iter().enumerate() {
if *field != path_2[i] {
prefix = false;
}
}
prefix
}
pub fn edges_consistent(&self, edge_1: Edge, edge_2: Edge) -> bool {
let path_1 = edge_1.2;
let path_2 = edge_2.2;
self.path_is_prefix(path_1.clone(), path_2.clone()) || self.path_is_prefix(path_2, path_1)
}
}