Skip to main content

cp_ast_core/structure/
node_id.rs

1use std::sync::atomic::{AtomicU64, Ordering};
2
3use serde::Serialize;
4
5static NEXT_ID: AtomicU64 = AtomicU64::new(1);
6
7/// Stable, unique identifier for AST nodes.
8///
9/// Each `NodeId` is globally unique within a process lifetime.
10/// Used for node identification, reference resolution, and diff comparison.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
12pub struct NodeId(u64);
13
14impl NodeId {
15    /// Create a new unique `NodeId`.
16    #[must_use]
17    pub fn new() -> Self {
18        Self(NEXT_ID.fetch_add(1, Ordering::Relaxed))
19    }
20
21    /// Create a `NodeId` from a raw value.
22    /// Used by arenas that manage their own ID allocation.
23    #[must_use]
24    pub fn from_raw(value: u64) -> Self {
25        Self(value)
26    }
27
28    /// Returns the raw numeric value of this ID.
29    #[must_use]
30    pub fn value(self) -> u64 {
31        self.0
32    }
33}
34
35impl Default for NodeId {
36    fn default() -> Self {
37        Self::new()
38    }
39}