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
use std::sync::atomic;
use std::sync::atomic::AtomicU64;

/// Generate a new, globally unique substitution ID
pub fn new_substitution_id() -> u32 {
    static ID: AtomicU64 = AtomicU64::new(0);
    let id = ID.fetch_add(1, atomic::Ordering::Relaxed);
    if id > u32::MAX as u64 {
        panic!(
            "Too many `Substitution` structs\n\
            \n\
            To allow caching across multiple results, we assign each \
            substitution a unique 32 bit integer. Now, so many substitutions \
            have been created that we cannot guarantee uniqueness anymore."
        );
    }

    id as u32
}

/// Substitution mapping variables to replacement functions
///
/// The intent behind substitution structs is to optimize the case where the
/// same substitution is applied multiple times. We would like to re-use apply
/// cache entries across these operations, and therefore, we need a compact
/// identifier for the substitution (provided by [`Self::id()`] here).
///
/// To create a substitution, you'll probably want to use [`Subst::new()`].
pub trait Substitution {
    /// Variable type
    type Var;
    /// Replacement type
    type Replacement;

    /// Get the ID of this substitution
    ///
    /// This unique identifier may safely be used as part of a cache key, i.e.,
    /// two different substitutions to be used with one manager must not have
    /// the same ID. (That two equal substitutions have the same ID would be
    /// ideal but is not required for correctness.)
    fn id(&self) -> u32;

    /// Iterate over pairs of variable and replacement
    fn pairs(&self) -> impl ExactSizeIterator<Item = (Self::Var, Self::Replacement)>;

    /// Map the substitution, e.g., to use different variable and replacement
    /// types
    ///
    /// `f` should be injective with respect to variables (the first component),
    /// i.e., two different variables should not be mapped to one. This is
    /// required to preserve that the substitution is a mapping from variables
    /// to replacement functions.
    #[inline]
    fn map<V, R, F>(&self, f: F) -> MapSubst<Self, F>
    where
        F: Fn((Self::Var, Self::Replacement)) -> (V, R),
    {
        MapSubst { inner: self, f }
    }
}

impl<T: Substitution> Substitution for &T {
    type Var = T::Var;
    type Replacement = T::Replacement;

    #[inline]
    fn id(&self) -> u32 {
        (*self).id()
    }
    #[inline]
    fn pairs(&self) -> impl ExactSizeIterator<Item = (Self::Var, Self::Replacement)> {
        (*self).pairs()
    }
}

/// Substitution mapping variables to replacement functions, created from slices
/// of functions
#[derive(Debug)]
pub struct Subst<'a, F> {
    id: u32,
    vars: &'a [F],
    replacements: &'a [F],
}

impl<F> Copy for Subst<'_, F> {}
impl<F> Clone for Subst<'_, F> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<'a, F> Substitution for Subst<'a, F> {
    type Var = &'a F;
    type Replacement = &'a F;

    #[inline]
    fn id(&self) -> u32 {
        self.id
    }

    #[inline]
    fn pairs(&self) -> impl ExactSizeIterator<Item = (Self::Var, Self::Replacement)> {
        self.vars.iter().zip(self.replacements)
    }
}

impl<'a, F> Subst<'a, F> {
    /// Create a new substitution to replace the i-th variable of `vars` by the
    /// i-th function in replacement
    ///
    /// All variables of `vars` should be distinct. Furthermore, variables must
    /// be handles for the respective decision diagram levels, e.g., the
    /// respective Boolean function for B(C)DDs, and a singleton set for ZBDDs.
    ///
    /// Panics if `vars` and `replacements` have different length
    #[track_caller]
    pub fn new(vars: &'a [F], replacements: &'a [F]) -> Self {
        assert_eq!(
            vars.len(),
            replacements.len(),
            "`vars` and `replacements` must have the same length"
        );

        Self {
            id: new_substitution_id(),
            vars,
            replacements,
        }
    }
}

/// Substitution mapping variables to replacement functions, created via
/// [`Substitution::map()`]
#[derive(Clone, Copy, Debug)]
pub struct MapSubst<'a, S: ?Sized, F> {
    inner: &'a S,
    f: F,
}

impl<V, R, S: Substitution + ?Sized, F: Fn((S::Var, S::Replacement)) -> (V, R)> Substitution
    for MapSubst<'_, S, F>
{
    type Var = V;
    type Replacement = R;

    #[inline]
    fn id(&self) -> u32 {
        self.inner.id()
    }

    #[inline]
    fn pairs(&self) -> impl ExactSizeIterator<Item = (Self::Var, Self::Replacement)> {
        self.inner.pairs().map(&self.f)
    }
}