1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Copyright (c) 2017 Fabian Schuiki
use std;
use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};

/// A positive, small ID assigned to nodes in the AST and derived data
/// structures. Used as a lightweight way to refer to individual nodes, e.g.
/// during symbol table construction and name resolution.
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
pub struct NodeId(u32);


impl NodeId {
	pub fn new(x: usize) -> NodeId {
		use std::u32;
		assert!(x < (u32::MAX as usize));
		NodeId(x as u32)
	}

	/// Allocate a new unused ID. The IDs generated by this function are
	/// monotonically increasing.
	pub fn alloc() -> NodeId {
		static NEXT_ID: AtomicUsize = ATOMIC_USIZE_INIT;
		NodeId::new(NEXT_ID.fetch_add(1, Ordering::SeqCst))
	}

	pub fn from_u32(x: u32) -> NodeId {
		NodeId(x)
	}

	pub fn as_usize(&self) -> usize {
		self.0 as usize
	}

	pub fn as_u32(&self) -> u32 {
		self.0
	}
}


impl std::fmt::Display for NodeId {
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
		write!(f, "{}", self.0)
	}
}