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!(
36                "weak reference points to a dropped value. Original object's name: `{}'",
37                self.debug_name
38            );
39            #[cfg(not(debug_assertions))]
40            unreachable!("weak reference points to a dropped value.");
41        };
42        r
43    }
44}
45
46/// From implementation with the same signature as `Rc::downgrade`.
47impl<T: GetName> From<&RRC<T>> for WRC<T> {
48    fn from(internal: &RRC<T>) -> Self {
49        Self {
50            internal: Rc::downgrade(internal),
51            #[cfg(debug_assertions)]
52            debug_name: internal.borrow().name(),
53        }
54    }
55}
56
57/// Clone the Weak reference inside the WRC.
58impl<T: GetName> Clone for WRC<T> {
59    fn clone(&self) -> Self {
60        Self {
61            internal: Weak::clone(&self.internal),
62            #[cfg(debug_assertions)]
63            debug_name: self.debug_name,
64        }
65    }
66}