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
use super::context::*;
use super::module::*;
use super::signal::*;

use std::cell::RefCell;
use std::collections::BTreeMap;
use std::hash::{Hash, Hasher};
use std::ptr;

/// An instance of a [`Module`], created by the [`Module`]::[`instance`] method.
///
/// # Examples
///
/// ```
/// use kaze::*;
///
/// let c = Context::new();
///
/// // Inner module (simple pass-through)
/// let inner = c.module("Inner");
/// inner.output("o", inner.input("i", 32));
///
/// // Outer module (wraps a single `Inner` instance)
/// let outer = c.module("Outer");
/// let inner_inst = outer.instance("inner_inst", "Inner");
/// inner_inst.drive_input("i", outer.input("i", 32));
/// outer.output("o", inner_inst.output("o"));
/// ```
///
/// [`instance`]: ./struct.Module.html#method.instance
/// [`Module`]: ./struct.Module.html
#[must_use]
pub struct Instance<'a> {
    pub(super) context: &'a Context<'a>,
    pub(super) module: &'a Module<'a>,

    pub(crate) instantiated_module: &'a Module<'a>,
    pub(crate) name: String,
    pub(crate) driven_inputs: RefCell<BTreeMap<String, &'a Signal<'a>>>,
}

impl<'a> Instance<'a> {
    /// Drives the input of this [`Module`] `Instance` specified by `name` with the given [`Signal`].
    ///
    /// # Panics
    ///
    /// Panics if `i` is from a different [`Module`] than `self`, if `name` specifies an input that doesn't exist on this `Instance`'s [`Module`], if this input is already driven on this `Instance`, or if `i`'s bit width differs from that of the input.
    ///
    /// # Examples
    ///
    /// ```
    /// use kaze::*;
    ///
    /// let c = Context::new();
    ///
    /// let inner = c.module("Inner");
    /// inner.output("o", inner.input("i", 32));
    ///
    /// let outer = c.module("Outer");
    /// let inner_inst = outer.instance("inner_inst", "Inner");
    /// // Drive inner_inst's "i" input with a 32-bit literal
    /// inner_inst.drive_input("i", outer.lit(0xfadebabeu32, 32));
    /// ```
    ///
    /// [`Module`]: ./struct.Module.html
    /// [`Signal`]: ./struct.Signal.html
    pub fn drive_input<S: Into<String>>(&'a self, name: S, i: &'a Signal<'a>) {
        let name = name.into();
        let mut driven_inputs = self.driven_inputs.borrow_mut();
        if !ptr::eq(self.module, i.module) {
            panic!("Attempted to drive an instance input with a signal from a different module.");
        }
        if !self.instantiated_module.inputs.borrow().contains_key(&name) {
            panic!("Attempted to drive an input called \"{}\" on an instance of \"{}\", but no such input with this name exists on this module.", name, self.instantiated_module.name);
        }
        if driven_inputs.contains_key(&name) {
            panic!("Attempted to drive an input called \"{}\" on an instance of \"{}\", but this input is already driven for this instance.", name, self.instantiated_module.name);
        }
        let input_bit_width = self.instantiated_module.inputs.borrow()[&name].bit_width();
        if input_bit_width != i.bit_width() {
            panic!("Attempted to drive an input called \"{}\" on an instance of \"{}\", but this input and the provided signal have different bit widths ({} and {}, respectively).", name, self.instantiated_module.name, input_bit_width, i.bit_width());
        }
        driven_inputs.insert(name, i);
    }

    /// Creates a [`Signal`] that represents this `Instance`'s output called `name`.
    ///
    /// # Panics
    ///
    /// Panics if `name` specifies an output that doesn't exist on this `Instance`'s [`Module`].
    ///
    /// # Examples
    ///
    /// ```
    /// use kaze::*;
    ///
    /// let c = Context::new();
    ///
    /// let inner = c.module("Inner");
    /// inner.output("o", inner.lit(true, 1));
    ///
    /// let outer = c.module("Outer");
    /// let inner_inst = outer.instance("inner_inst", "Inner");
    /// // Forward inner_inst's "o" output to a new output on outer with the same name
    /// outer.output("o", inner_inst.output("o"));
    /// ```
    ///
    /// [`Module`]: ./struct.Module.html
    /// [`Signal`]: ./struct.Signal.html
    pub fn output<S: Into<String>>(&'a self, name: S) -> &Signal<'a> {
        let name = name.into();
        if !self
            .instantiated_module
            .outputs
            .borrow()
            .contains_key(&name)
        {
            panic!("Attempted to create a signal for an output called \"{}\" on an instance of \"{}\", but no such output with this name exists on this module.", name, self.instantiated_module.name);
        }
        self.context.signal_arena.alloc(Signal {
            context: self.context,
            module: self.module,

            data: SignalData::InstanceOutput {
                instance: self,
                name,
            },
        })
    }
}

impl<'a> Eq for &'a Instance<'a> {}

impl<'a> Hash for &'a Instance<'a> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        state.write_usize(*self as *const _ as usize)
    }
}

impl<'a> PartialEq for &'a Instance<'a> {
    fn eq(&self, other: &Self) -> bool {
        ptr::eq(*self, *other)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[should_panic(
        expected = "Attempted to drive an instance input with a signal from a different module."
    )]
    fn drive_input_different_module_error() {
        let c = Context::new();

        let inner = c.module("Inner");
        let _ = inner.input("a", 1);

        let m1 = c.module("A");
        let i1 = m1.input("a", 1);

        let m2 = c.module("B");
        let inner_inst = m2.instance("inner_inst", "Inner");

        // Panic
        inner_inst.drive_input("a", i1);
    }

    #[test]
    #[should_panic(
        expected = "Attempted to drive an input called \"a\" on an instance of \"Inner\", but no such input with this name exists on this module."
    )]
    fn drive_input_nonexistent_input_error() {
        let c = Context::new();

        let _ = c.module("Inner");

        let m = c.module("A");
        let inner_inst = m.instance("inner_inst", "Inner");

        // Panic
        inner_inst.drive_input("a", m.input("i", 1));
    }

    #[test]
    #[should_panic(
        expected = "Attempted to drive an input called \"a\" on an instance of \"Inner\", but this input is already driven for this instance."
    )]
    fn drive_input_already_driven_error() {
        let c = Context::new();

        let inner = c.module("Inner");
        let _ = inner.input("a", 1);

        let m = c.module("A");
        let inner_inst = m.instance("inner_inst", "Inner");

        inner_inst.drive_input("a", m.input("i1", 1));

        // Panic
        inner_inst.drive_input("a", m.input("i2", 1));
    }

    #[test]
    #[should_panic(
        expected = "Attempted to drive an input called \"a\" on an instance of \"Inner\", but this input and the provided signal have different bit widths (1 and 32, respectively)."
    )]
    fn drive_input_incompatible_bit_widths_error() {
        let c = Context::new();

        let inner = c.module("Inner");
        let _ = inner.input("a", 1);

        let m = c.module("A");
        let inner_inst = m.instance("inner_inst", "Inner");

        // Panic
        inner_inst.drive_input("a", m.input("i1", 32));
    }

    #[test]
    #[should_panic(
        expected = "Attempted to create a signal for an output called \"nope\" on an instance of \"Inner\", but no such output with this name exists on this module."
    )]
    fn output_nonexistent_output_error() {
        let c = Context::new();

        let _ = c.module("Inner");

        let m = c.module("A");
        let inner_inst = m.instance("inner_inst", "Inner");

        // Panic
        let _ = inner_inst.output("nope");
    }
}