Refactor NodeIdentity to use unique IDs
The `NodeIdentity` struct has been refactored to use a unique `id` field generated by an atomic counter. This ensures that each `NodeIdentity` instance is distinct, even if it has the same `SourceLocation`. The `location` field is now optional, allowing for anonymous nodes. This change improves the reliability of identity comparisons and provides a more robust way to manage AST node identities.
This commit is contained in:
+43
-3
@@ -14,14 +14,54 @@ pub struct SourceLocation {
|
||||
pub col: u32,
|
||||
}
|
||||
|
||||
/// Shared identity for nodes (Location, etc.)
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
/// Shared identity for nodes. The identity is defined by the object instance (unique ID).
|
||||
/// SourceLocation is kept as optional metadata.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NodeIdentity {
|
||||
pub location: SourceLocation,
|
||||
pub id: u64,
|
||||
pub location: Option<SourceLocation>,
|
||||
}
|
||||
|
||||
impl PartialEq for NodeIdentity {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.id == other.id
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for NodeIdentity {}
|
||||
|
||||
impl std::hash::Hash for NodeIdentity {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.id.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
pub type Identity = Rc<NodeIdentity>;
|
||||
|
||||
static NODE_ID_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
|
||||
impl NodeIdentity {
|
||||
pub fn next_id() -> u64 {
|
||||
NODE_ID_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Creates a new unique identity at the given location.
|
||||
pub fn new(location: SourceLocation) -> Identity {
|
||||
Rc::new(NodeIdentity {
|
||||
id: Self::next_id(),
|
||||
location: Some(location),
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates a new unique identity without location metadata (for synthetic nodes).
|
||||
pub fn anonymous() -> Identity {
|
||||
Rc::new(NodeIdentity {
|
||||
id: Self::next_id(),
|
||||
location: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Interned string identifier
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct Keyword(pub u32);
|
||||
|
||||
Reference in New Issue
Block a user