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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

//! This module defines traits and representations of domains used in dataflow analysis.

use im::{ordmap, ordset, OrdMap, OrdSet};
use itertools::Itertools;
use std::{
    borrow::Borrow,
    collections::{BTreeMap, BTreeSet},
    fmt::Debug,
    ops::{Deref, DerefMut},
};

// ================================================================================================
// Abstract Domains

/// Represents the abstract outcome of a join.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JoinResult {
    /// The left operand subsumes the right operand: L union R == L.
    Unchanged,
    /// The left operand does not subsume the right one and was changed as part of the join.
    Changed,
}

impl JoinResult {
    /// Build the least upper bound of two join results, where `Unchanged` is bottom element of the
    /// semilattice.
    pub fn combine(self, other: JoinResult) -> JoinResult {
        use JoinResult::*;
        match (self, other) {
            (Unchanged, Unchanged) => Unchanged,
            _ => Changed,
        }
    }
}

/// A trait to be implemented by domains which support a join.
pub trait AbstractDomain {
    // TODO: would be cool to add a derive(Join) macro for this
    fn join(&mut self, other: &Self) -> JoinResult;
}

// ================================================================================================
// Predefined Domain Types

// As the underlying implementation of the below types we use the collections from the `im`(mutable)
// crate (`im::OrdSet` and `im::OrdMap`), a representation which supports structure sharing.
// This is important because in data flow analysis we often refine a set or map
// value in each step of the analysis, e.g. adding a single element to a larger collection, while
// the original collection still need to be available at the previous program point.

// ------------------------------------------------------------------------------------------------
// Set Type

/// Implements a set domain.
#[derive(Clone, Eq, Ord, PartialEq, PartialOrd)]
pub struct SetDomain<E: Ord + Clone>(OrdSet<E>);

impl<E: Ord + Clone> Default for SetDomain<E> {
    fn default() -> Self {
        Self(OrdSet::default())
    }
}

impl<E: Ord + Clone> From<OrdSet<E>> for SetDomain<E> {
    fn from(ord_set: OrdSet<E>) -> Self {
        Self(ord_set)
    }
}

impl<E: Ord + Clone> AsRef<OrdSet<E>> for SetDomain<E> {
    fn as_ref(&self) -> &OrdSet<E> {
        &self.0
    }
}

impl<E: Ord + Clone> Borrow<OrdSet<E>> for SetDomain<E> {
    fn borrow(&self) -> &OrdSet<E> {
        self.as_ref()
    }
}

impl<E: Ord + Clone> Deref for SetDomain<E> {
    type Target = OrdSet<E>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<E: Ord + Clone> DerefMut for SetDomain<E> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<E: Ord + Clone + Debug> Debug for SetDomain<E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self.0)
    }
}

impl<E: Ord + Clone> std::iter::FromIterator<E> for SetDomain<E> {
    fn from_iter<I: IntoIterator<Item = E>>(iter: I) -> Self {
        let mut s = SetDomain::default();
        for e in iter {
            s.insert(e);
        }
        s
    }
}

impl<E: Ord + Clone> std::iter::IntoIterator for SetDomain<E> {
    type Item = E;
    type IntoIter = im::ordset::ConsumingIter<E>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<E: Ord + Clone> AbstractDomain for SetDomain<E> {
    fn join(&mut self, other: &Self) -> JoinResult {
        let mut change = JoinResult::Unchanged;
        for e in other.iter() {
            if self.insert(e.clone()).is_none() {
                change = JoinResult::Changed;
            }
        }
        change
    }
}

impl<E: Ord + Clone> From<BTreeSet<E>> for SetDomain<E> {
    fn from(s: BTreeSet<E>) -> Self {
        s.into_iter().collect()
    }
}

impl<E: Ord + Clone> SetDomain<E> {
    pub fn singleton(e: E) -> Self {
        ordset!(e).into()
    }

    /// Implements set difference, which is not following standard APIs for rust sets in OrdSet
    pub fn difference<'a>(&'a self, other: &'a Self) -> impl Iterator<Item = &'a E> {
        self.iter().filter(move |e| !other.contains(e))
    }

    /// Implements is_disjoint which is not available in OrdSet
    pub fn is_disjoint(&self, other: &Self) -> bool {
        self.iter().all(move |e| !other.contains(e))
    }
}

// ------------------------------------------------------------------------------------------------
// Map Type

#[derive(Clone, Eq, Ord, PartialEq, PartialOrd)]
pub struct MapDomain<K: Ord, V: AbstractDomain>(OrdMap<K, V>);

impl<K: Ord + Clone, V: AbstractDomain + Clone> Default for MapDomain<K, V> {
    fn default() -> Self {
        Self(OrdMap::default())
    }
}

impl<K: Ord + Clone, V: AbstractDomain + Clone> From<OrdMap<K, V>> for MapDomain<K, V> {
    fn from(ord_map: OrdMap<K, V>) -> Self {
        Self(ord_map)
    }
}

impl<K: Ord + Clone, V: AbstractDomain + Clone> AsRef<OrdMap<K, V>> for MapDomain<K, V> {
    fn as_ref(&self) -> &OrdMap<K, V> {
        &self.0
    }
}

impl<K: Ord + Clone, V: AbstractDomain + Clone> Borrow<OrdMap<K, V>> for MapDomain<K, V> {
    fn borrow(&self) -> &OrdMap<K, V> {
        self.as_ref()
    }
}

impl<K: Ord + Clone, V: AbstractDomain + Clone> Deref for MapDomain<K, V> {
    type Target = OrdMap<K, V>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<K: Ord + Clone, V: AbstractDomain + Clone> DerefMut for MapDomain<K, V> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<K: Ord + Clone + Debug, V: AbstractDomain + Clone + Debug> Debug for MapDomain<K, V> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self.0)
    }
}

impl<K: Ord + Clone, V: AbstractDomain + Clone> std::iter::FromIterator<(K, V)>
    for MapDomain<K, V>
{
    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
        let mut s = MapDomain::default();
        for (k, v) in iter {
            s.insert(k, v);
        }
        s
    }
}

impl<K: Ord + Clone, V: AbstractDomain + Clone> std::iter::IntoIterator for MapDomain<K, V> {
    type Item = (K, V);
    type IntoIter = im::ordmap::ConsumingIter<(K, V)>;
    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<K: Ord + Clone, V: AbstractDomain + Clone> AbstractDomain for MapDomain<K, V> {
    fn join(&mut self, other: &Self) -> JoinResult {
        let mut change = JoinResult::Unchanged;
        for (k, v) in other.iter() {
            change = change.combine(self.insert_join(k.clone(), v.clone()));
        }
        change
    }
}

impl<K: Ord + Clone, V: AbstractDomain + Clone> From<BTreeMap<K, V>> for MapDomain<K, V> {
    fn from(m: BTreeMap<K, V>) -> Self {
        m.into_iter().collect()
    }
}

impl<K: Ord + Clone, V: AbstractDomain + Clone> MapDomain<K, V> {
    /// Construct a singleton map.
    pub fn singleton(k: K, v: V) -> MapDomain<K, V> {
        (ordmap! {k => v}).into()
    }

    /// Join `v` with self[k] if `k` is bound, insert `v` otherwise
    pub fn insert_join(&mut self, k: K, v: V) -> JoinResult {
        let mut change = JoinResult::Unchanged;
        self.0
            .entry(k)
            .and_modify(|old_v| {
                change = old_v.join(&v);
            })
            .or_insert_with(|| {
                change = JoinResult::Changed;
                v
            });
        change
    }
}

impl<K: Ord + Clone, V: AbstractDomain + Clone + PartialEq> MapDomain<K, V> {
    /// Updates the values in the range of the map using the given function. Notice
    /// that with other kind of map representations we would use `iter_mut` for this,
    /// but this is not available in OrdMap for obvious reasons (because entries are shared),
    /// so we need to use this pattern here instead.
    pub fn update_values(&mut self, mut f: impl FnMut(&mut V)) {
        // Commpute the key-values which actually changed. If the change is small, we preserve
        // structure sharing.
        let new_values = self
            .iter()
            .filter_map(|(k, v)| {
                let mut v_new = v.clone();
                f(&mut v_new);
                if v != &v_new {
                    Some((k.clone(), v_new))
                } else {
                    None
                }
            })
            .collect_vec();
        self.extend(new_values.into_iter());
    }
}