calyx_ir/
common.rs

1use calyx_utils::GetName;
2#[cfg(debug_assertions)]
3use calyx_utils::Id;
4use std::cell::RefCell;
5use std::rc::{Rc, Weak};
6
7/// Alias for a RefCell contained in an Rc reference.
8#[allow(clippy::upper_case_acronyms)]
9pub type RRC<T> = Rc<RefCell<T>>;
10
11/// Construct a new RRC.
12pub fn rrc<T>(t: T) -> RRC<T> {
13    Rc::new(RefCell::new(t))
14}
15
16/// A Wrapper for a weak RefCell pointer.
17/// Used by parent pointers in the internal representation.
18#[allow(clippy::upper_case_acronyms)]
19#[derive(Debug)]
20pub struct WRC<T>
21where
22    T: GetName,
23{
24    pub(super) internal: Weak<RefCell<T>>,
25    #[cfg(debug_assertions)]
26    debug_name: Id,
27}
28
29impl<T: GetName> WRC<T> {
30    /// Convinience method to upgrade and extract the underlying internal weak
31    /// pointer.
32    pub fn upgrade(&self) -> RRC<T> {
33        let Some(r) = self.internal.upgrade() else {
34            #[cfg(debug_assertions)]
35            unreachable!("weak reference points to a dropped value. Original object's name: `{}'", self.debug_name);
36            #[cfg(not(debug_assertions))]
37            unreachable!("weak reference points to a dropped value.");
38        };
39        r
40    }
41}
42
43/// From implementation with the same signature as `Rc::downgrade`.
44impl<T: GetName> From<&RRC<T>> for WRC<T> {
45    fn from(internal: &RRC<T>) -> Self {
46        Self {
47            internal: Rc::downgrade(internal),
48            #[cfg(debug_assertions)]
49            debug_name: internal.borrow().name(),
50        }
51    }
52}
53
54/// Clone the Weak reference inside the WRC.
55impl<T: GetName> Clone for WRC<T> {
56    fn clone(&self) -> Self {
57        Self {
58            internal: Weak::clone(&self.internal),
59            #[cfg(debug_assertions)]
60            debug_name: self.debug_name,
61        }
62    }
63}