moore_common/
id.rs

1// Copyright (c) 2016-2021 Fabian Schuiki
2use std::sync::atomic::{AtomicUsize, Ordering};
3
4/// A positive, small ID assigned to nodes in the AST and derived data
5/// structures. Used as a lightweight way to refer to individual nodes, e.g.
6/// during symbol table construction and name resolution.
7#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
8pub struct NodeId(u32);
9
10impl NodeId {
11    pub fn new(x: usize) -> NodeId {
12        use std::u32;
13        assert!(x < (u32::MAX as usize));
14        NodeId(x as u32)
15    }
16
17    /// Allocate a new unused ID. The IDs generated by this function are
18    /// monotonically increasing.
19    pub fn alloc() -> NodeId {
20        static NEXT_ID: AtomicUsize = AtomicUsize::new(0);
21        NodeId::new(NEXT_ID.fetch_add(1, Ordering::SeqCst))
22    }
23
24    pub fn from_u32(x: u32) -> NodeId {
25        NodeId(x)
26    }
27
28    pub fn as_usize(&self) -> usize {
29        self.0 as usize
30    }
31
32    pub fn as_u32(&self) -> u32 {
33        self.0
34    }
35}
36
37impl std::fmt::Debug for NodeId {
38    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
39        write!(f, "n{}", self.0)
40    }
41}