kodept_ast/graph/
node_id.rs

1use std::fmt::{Debug, Formatter};
2use std::hash::{Hash, Hasher};
3
4use derive_more::{Display, From};
5#[cfg(feature = "serde")]
6use serde::{Deserialize, Serialize};
7
8use slotgraph::{Key, NodeKey};
9
10use crate::graph::{AnyNode, SubEnum};
11
12#[derive(Display, From)]
13#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
14#[cfg_attr(feature = "serde", serde(transparent))]
15#[repr(transparent)]
16pub struct NodeId<Node>(Key<Node>);
17
18pub type GenericNodeId = NodeId<AnyNode>;
19pub type GenericNodeKey = Key<AnyNode>;
20
21impl From<GenericNodeId> for Key<AnyNode> {
22    fn from(value: GenericNodeId) -> Self {
23        value.0
24    }
25}
26
27impl<T> From<NodeKey> for NodeId<T> {
28    fn from(value: NodeKey) -> Self {
29        NodeId(value.into())
30    }
31}
32
33impl<T> From<NodeId<T>> for NodeKey {
34    fn from(value: NodeId<T>) -> Self {
35        value.0.into()
36    }
37}
38
39impl<T> NodeId<T> {
40    pub fn null() -> Self {
41        Self(Key::null())
42    }
43
44    pub fn cast<U>(self) -> NodeId<U>
45    where
46        U: TryFrom<T> + SubEnum,
47    {
48        NodeId(self.0.coerce())
49    }
50}
51
52impl<T: Into<AnyNode>> NodeId<T> {
53    pub fn widen(self) -> GenericNodeId {
54        NodeId(self.0.coerce())
55    }
56}
57
58impl GenericNodeId {
59    pub fn coerce<U>(self) -> NodeId<U>
60    where
61        U: SubEnum,
62    {
63        NodeId(self.0.coerce_unchecked())
64    }
65}
66
67impl GenericNodeId {
68    pub fn narrow<T: TryFrom<AnyNode>>(self) -> NodeId<T> {
69        NodeId(self.0.coerce())
70    }
71}
72
73impl<T> Debug for NodeId<T> {
74    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
75        write!(f, "{}", self.0)
76    }
77}
78
79impl<T> Hash for NodeId<T> {
80    fn hash<H: Hasher>(&self, state: &mut H) {
81        self.0.hash(state);
82    }
83}
84
85impl<T> PartialEq for NodeId<T> {
86    fn eq(&self, other: &Self) -> bool {
87        self.0.eq(&other.0)
88    }
89}
90
91impl<T> Eq for NodeId<T> {}
92
93impl<T> Clone for NodeId<T> {
94    fn clone(&self) -> Self {
95        *self
96    }
97}
98
99impl<T> Copy for NodeId<T> {}