topstitch 0.96.0

Stitch together Verilog modules with Rust
Documentation
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
// SPDX-License-Identifier: Apache-2.0

use parking_lot::RwLock;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, Weak};

use crate::connection::PortSliceConnections;
use crate::io::IO;
use crate::mod_inst::HierPathElem;
use crate::{
    ConvertibleToPortSlice, Coordinate, MetadataKey, MetadataValue, ModDef, ModDefCore, ModInst,
    PhysicalPin, PortSlice,
};

mod connect;
mod export;
mod feedthrough;
mod tieoff;
mod trace;

#[derive(Clone, Debug)]
pub enum PortDirectionality {
    Driver,
    Receiver,
    InOut,
}

impl PortDirectionality {
    pub(crate) fn compatible_with(&self, other: &PortDirectionality) -> bool {
        matches!(
            (self, other),
            (PortDirectionality::InOut, _)
                | (_, PortDirectionality::InOut)
                | (PortDirectionality::Driver, PortDirectionality::Receiver)
                | (PortDirectionality::Receiver, PortDirectionality::Driver)
        )
    }
}

/// Represents a port on a module definition or a module instance.
#[derive(Clone, Debug)]
pub enum Port {
    ModDef {
        mod_def_core: Weak<RwLock<ModDefCore>>,
        name: String,
    },
    ModInst {
        hierarchy: Vec<HierPathElem>,
        port_name: String,
    },
}

impl PartialEq for Port {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (
                Port::ModDef {
                    mod_def_core: a_core,
                    name: a_name,
                },
                Port::ModDef {
                    mod_def_core: b_core,
                    name: b_name,
                },
            ) => match (a_core.upgrade(), b_core.upgrade()) {
                (Some(a_rc), Some(b_rc)) => Arc::ptr_eq(&a_rc, &b_rc) && (a_name == b_name),
                _ => false,
            },
            (
                Port::ModInst {
                    hierarchy: a_hier,
                    port_name: a_port,
                },
                Port::ModInst {
                    hierarchy: b_hier,
                    port_name: b_port,
                },
            ) => a_hier == b_hier && (a_port == b_port),
            _ => false,
        }
    }
}

impl Eq for Port {}

impl Hash for Port {
    fn hash<H: Hasher>(&self, state: &mut H) {
        match self {
            Port::ModDef { name, mod_def_core } => {
                // Hash pointer identity and name
                if let Some(rc) = mod_def_core.upgrade() {
                    Arc::as_ptr(&rc).hash(state);
                } else {
                    (0usize).hash(state);
                }
                name.hash(state);
            }
            Port::ModInst {
                port_name,
                hierarchy,
            } => {
                // Hash the chain of instance frame pointer identities and names, then port name
                for frame in hierarchy {
                    if let Some(rc) = frame.mod_def_core.upgrade() {
                        Arc::as_ptr(&rc).hash(state);
                    } else {
                        (0usize).hash(state);
                    }
                    frame.inst_name.hash(state);
                }
                port_name.hash(state);
            }
        }
    }
}

impl Port {
    /// Returns the name this port has in its (parent) module definition.
    pub fn name(&self) -> &str {
        match self {
            Port::ModDef { name, .. } => name,
            Port::ModInst { port_name, .. } => port_name,
        }
    }

    pub fn set_metadata(
        &self,
        key: impl Into<MetadataKey>,
        value: impl Into<MetadataValue>,
    ) -> Self {
        let key = key.into();
        let value = value.into();
        match self {
            Port::ModDef { .. } => {
                let core_rc = self.get_mod_def_core_where_declared();
                let mut core = core_rc.write();
                core.mod_def_port_metadata
                    .entry(self.name().to_string())
                    .or_default()
                    .insert(key, value);
            }
            Port::ModInst { .. } => {
                let inst_name = self
                    .inst_name()
                    .expect("Port::ModInst hierarchy cannot be empty")
                    .to_string();
                let core_rc = self.get_mod_def_core();
                let mut core = core_rc.write();
                core.mod_inst_port_metadata
                    .entry(inst_name)
                    .or_default()
                    .entry(self.name().to_string())
                    .or_default()
                    .insert(key, value);
            }
        }
        self.clone()
    }

    pub fn get_metadata(&self, key: impl AsRef<str>) -> Option<MetadataValue> {
        match self {
            Port::ModDef { .. } => self
                .get_mod_def_core_where_declared()
                .read()
                .mod_def_port_metadata
                .get(self.name())
                .and_then(|metadata| metadata.get(key.as_ref()).cloned()),
            Port::ModInst { .. } => {
                let inst_name = self
                    .inst_name()
                    .expect("Port::ModInst hierarchy cannot be empty");
                self.get_mod_def_core()
                    .read()
                    .mod_inst_port_metadata
                    .get(inst_name)
                    .and_then(|ports| ports.get(self.name()))
                    .and_then(|metadata| metadata.get(key.as_ref()).cloned())
            }
        }
    }

    pub fn clear_metadata(&self, key: impl AsRef<str>) -> Self {
        match self {
            Port::ModDef { .. } => {
                let core_rc = self.get_mod_def_core_where_declared();
                let mut core = core_rc.write();
                if let Some(metadata) = core.mod_def_port_metadata.get_mut(self.name()) {
                    metadata.remove(key.as_ref());
                    if metadata.is_empty() {
                        core.mod_def_port_metadata.remove(self.name());
                    }
                }
            }
            Port::ModInst { .. } => {
                let inst_name = self
                    .inst_name()
                    .expect("Port::ModInst hierarchy cannot be empty")
                    .to_string();
                let core_rc = self.get_mod_def_core();
                let mut core = core_rc.write();
                if let Some(ports) = core.mod_inst_port_metadata.get_mut(&inst_name) {
                    if let Some(metadata) = ports.get_mut(self.name()) {
                        metadata.remove(key.as_ref());
                        if metadata.is_empty() {
                            ports.remove(self.name());
                        }
                    }
                    if ports.is_empty() {
                        core.mod_inst_port_metadata.remove(&inst_name);
                    }
                }
            }
        }
        self.clone()
    }

    /// Returns the IO enum associated with this Port.
    pub fn io(&self) -> IO {
        match self {
            Port::ModDef { mod_def_core, name } => {
                mod_def_core.upgrade().unwrap().read().ports[name].clone()
            }
            Port::ModInst {
                hierarchy,
                port_name,
                ..
            } => {
                let inst_frame = hierarchy
                    .last()
                    .expect("Port::ModInst hierarchy cannot be empty");
                inst_frame.mod_def_core.upgrade().unwrap().read().instances
                    [inst_frame.inst_name.as_str()]
                .read()
                .ports[port_name.as_str()]
                .clone()
            }
        }
    }

    pub(crate) fn assign_to_inst(&self, inst: &ModInst) -> Port {
        match self {
            Port::ModDef { name, .. } => Port::ModInst {
                hierarchy: inst.hierarchy.clone(),
                port_name: name.clone(),
            },
            _ => panic!("Already assigned to an instance."),
        }
    }

    pub(crate) fn is_driver(&self) -> bool {
        match self {
            Port::ModDef { .. } => matches!(self.io(), IO::Input(_)),
            Port::ModInst { .. } => matches!(self.io(), IO::Output(_)),
        }
    }

    pub(crate) fn get_mod_def_core(&self) -> Arc<RwLock<ModDefCore>> {
        match self {
            Port::ModDef { mod_def_core, .. } => mod_def_core.upgrade().unwrap(),
            Port::ModInst { hierarchy, .. } => hierarchy
                .last()
                .expect("Port::ModInst hierarchy cannot be empty")
                .mod_def_core
                .upgrade()
                .expect("Containing ModDefCore has been dropped"),
        }
    }

    pub(crate) fn get_mod_def_where_declared(&self) -> ModDef {
        ModDef {
            core: self.get_mod_def_core_where_declared(),
        }
    }

    pub(crate) fn get_mod_def_core_where_declared(&self) -> Arc<RwLock<ModDefCore>> {
        match self {
            Port::ModDef { mod_def_core, .. } => mod_def_core.upgrade().unwrap(),
            Port::ModInst { hierarchy, .. } => {
                let last = hierarchy.last().unwrap();
                last.mod_def_core
                    .upgrade()
                    .unwrap()
                    .read()
                    .instances
                    .get(last.inst_name.as_str())
                    .unwrap()
                    .clone()
            }
        }
    }

    /// Returns a new [`Port::ModInst`] with the same port name, but the
    /// provided hierarchy.
    pub(crate) fn as_mod_inst_port(&self, hierarchy: Vec<HierPathElem>) -> Port {
        Port::ModInst {
            hierarchy,
            port_name: self.name().to_string(),
        }
    }

    /// Returns a new [`Port::ModDef`] with the same port name, but a module
    /// definition pointer that corresponds to the module where the port is
    /// declared. For example, if `top` instantiates `a` as `a_inst` and
    /// `a_inst` has a port `x`, calling this function on `top.a_inst.x` will
    /// return effectively return `a.x` (i.e., the port on the module definition
    /// of `a`).
    pub(crate) fn as_mod_def_port(&self) -> Port {
        Port::ModDef {
            mod_def_core: Arc::downgrade(&self.get_mod_def_core_where_declared()),
            name: self.name().to_string(),
        }
    }

    pub(crate) fn get_port_connections_define_if_missing(
        &self,
    ) -> Arc<RwLock<PortSliceConnections>> {
        let core_rc = self.get_mod_def_core();
        let mut core = core_rc.write();
        match self {
            Port::ModDef { .. } => core
                .mod_def_connections
                .entry(self.name().to_string())
                .or_default()
                .clone(),
            Port::ModInst { .. } => core
                .mod_inst_connections
                .entry(self.inst_name().unwrap().to_string())
                .or_default()
                .entry(self.name().to_string())
                .or_default()
                .clone(),
        }
    }

    pub(crate) fn get_port_connections(&self) -> Option<Arc<RwLock<PortSliceConnections>>> {
        let core_rc = self.get_mod_def_core();
        let core = core_rc.read();
        match self {
            Port::ModDef { .. } => core
                .mod_def_connections
                .get(&self.name().to_string())
                .cloned(),
            Port::ModInst { .. } => core
                .mod_inst_connections
                .get(&self.inst_name().unwrap().to_string())
                .and_then(|connections| connections.get(&self.name().to_string()).cloned()),
        }
    }

    pub fn get_mod_inst(&self) -> Option<ModInst> {
        match self {
            Port::ModInst { hierarchy, .. } => Some(ModInst {
                hierarchy: hierarchy.clone(),
            }),
            _ => None,
        }
    }

    pub(crate) fn inst_name(&self) -> Option<&str> {
        match self {
            Port::ModInst { hierarchy, .. } => {
                hierarchy.last().map(|frame| frame.inst_name.as_str())
            }
            _ => None,
        }
    }

    pub(crate) fn get_port_name(&self) -> String {
        match self {
            Port::ModDef { name, .. } => name.clone(),
            Port::ModInst { port_name, .. } => port_name.clone(),
        }
    }

    pub(crate) fn debug_string(&self) -> String {
        match self {
            Port::ModDef { name, mod_def_core } => {
                format!("{}.{}", mod_def_core.upgrade().unwrap().read().name, name)
            }
            Port::ModInst { port_name, .. } => {
                let inst = self
                    .get_mod_inst()
                    .expect("Port::ModInst hierarchy cannot be empty");
                format!("{}.{}", inst.debug_string(), port_name)
            }
        }
    }

    pub fn has_physical_pin(&self) -> bool {
        self.to_port_slice().has_physical_pin()
    }

    pub fn get_physical_pin(&self) -> PhysicalPin {
        self.to_port_slice().get_physical_pin()
    }

    pub fn get_coordinate(&self) -> Coordinate {
        self.get_physical_pin().translation()
    }

    pub(crate) fn debug_string_with_width(&self) -> String {
        format!("{}[{}:{}]", self.debug_string(), self.io().width() - 1, 0)
    }

    /// Returns a slice of this port from `msb` down to `lsb`, inclusive.
    pub fn slice(&self, msb: usize, lsb: usize) -> PortSlice {
        if msb >= self.io().width() || lsb > msb {
            panic!(
                "Invalid slice [{}:{}] of port {}",
                msb,
                lsb,
                self.debug_string_with_width()
            );
        }
        PortSlice {
            port: self.clone(),
            msb,
            lsb,
        }
    }

    /// Returns a single-bit slice of this port at the specified index.
    pub fn bit(&self, index: usize) -> PortSlice {
        self.slice(index, index)
    }

    /// Splits this port into `n` equal slices, returning a vector of port
    /// slices. For example, if this port is 8-bit wide and `n` is 4, this will
    /// return a vector of 4 port slices, each 2 bits wide: `[1:0]`, `[3:2]`,
    /// `[5:4]`, and `[7:6]`.
    pub fn subdivide(&self, n: usize) -> Vec<PortSlice> {
        self.to_port_slice().subdivide(n)
    }

    /// Returns an ordered list of `(port name, bit index)` pairs covering every
    /// bit of this port.
    pub fn to_bits(&self) -> Vec<(&str, usize)> {
        let mut bits = Vec::new();
        for i in 0..self.io().width() {
            bits.push((self.name(), i));
        }
        bits
    }

    pub(crate) fn get_directionality(&self) -> PortDirectionality {
        match self {
            Port::ModDef { .. } => match self.io() {
                IO::Input(_) => PortDirectionality::Driver,
                IO::Output(_) => PortDirectionality::Receiver,
                IO::InOut(_) => PortDirectionality::InOut,
            },
            Port::ModInst { .. } => match self.io() {
                IO::Input(_) => PortDirectionality::Receiver,
                IO::Output(_) => PortDirectionality::Driver,
                IO::InOut(_) => PortDirectionality::InOut,
            },
        }
    }

    /// Places this port based on what has been connected to it.
    pub fn place_abutted(&self) {
        self.to_port_slice().place_abutted();
    }

    /// Places this port abutted to the specified port or port slice.
    pub fn place_abutted_to<T: ConvertibleToPortSlice>(&self, other: T) {
        self.to_port_slice().place_abutted_to(other);
    }

    /// For each bit in this port, trace its connectivity to determine what
    /// existing pin it is connected to, and then place a new pin for the
    /// port bit that overlaps the connected pin.
    pub fn place_overlapped(&self, pin: &PhysicalPin) {
        self.to_port_slice().place_overlapped(pin);
    }

    /// For each bit `i` in this port, place a new pin that overlaps the `i`-th
    /// bit of `other`.
    pub fn place_overlapped_with<T: ConvertibleToPortSlice>(&self, other: T, pin: &PhysicalPin) {
        self.to_port_slice().place_overlapped_with(other, pin);
    }

    /// Places this port across from the ModDef port it is directly connected
    /// to within the same module.
    pub fn place_across(&self) {
        self.to_port_slice().place_across();
    }

    /// Places this port across from the specified port or port slice.
    pub fn place_across_from<T: ConvertibleToPortSlice>(&self, other: T) {
        self.to_port_slice().place_across_from(other);
    }
}

impl ConvertibleToPortSlice for Port {
    fn to_port_slice(&self) -> PortSlice {
        PortSlice {
            port: self.clone(),
            msb: self.io().width() - 1,
            lsb: 0,
        }
    }
}