Skip to main content

wright/source_tracking/
mod.rs

1//! Types and traits for tracking source code fed to the wright compiler.
2
3use self::source::Source;
4use dashmap::DashMap;
5use source::SourceId;
6use std::sync::Arc;
7
8pub mod filename;
9pub mod fragment;
10pub mod immutable_string;
11pub mod source;
12
13/// A reference to a [Source] in a [SourceMap].
14pub type SourceRef = Arc<Source>;
15
16/// Storage for [Source]s used and referenced in compiling a wright project.
17///
18/// [Clone]ing is cheap, since this uses an [Arc] internally.
19#[derive(Debug, Default, Clone)]
20pub struct SourceMap {
21    /// Internally, we use [DashMap] for a concurrent hashmap from [Source::id]s to their [Arc]'d
22    ///
23    /// Each source is wrapped in an [Arc] to make them all accessible without holding a reference to this map
24    /// directly.
25    inner: Arc<DashMap<SourceId, SourceRef>>,
26}
27
28impl SourceMap {
29    /// Construct a new empty [SourceMap].
30    pub fn new() -> Self {
31        Default::default()
32    }
33
34    /// Add a [Source] to this [SourceMap] and get a [SourceRef] to it after it's added.
35    pub fn add(&self, source: Source) -> SourceRef {
36        // Put the source in an Arc.
37        let source: SourceRef = Arc::new(source);
38        // Push the souce to the internal Vec.
39        self.inner.insert(source.id, Arc::clone(&source));
40        // Return the now-Arc'd source.
41        source
42    }
43
44    /// Add a [Source] that has already been wrapped in a [SourceRef] to this [SourceMap].
45    /// If it's already in the map, this does nothing.
46    pub fn add_ref(&self, source: SourceRef) {
47        self.inner.insert(source.id, source);
48    }
49
50    /// Get a reference to a [Source] stored in this [SourceMap] using its [Source::id].
51    ///
52    /// This is currently `O(1)` since [SourceMap] uses a [DashMap] internally.
53    ///
54    /// Returns [None] if the [Source] with the given [Source::id] is not in this [SourceMap].
55    pub fn get(&self, id: SourceId) -> Option<SourceRef> {
56        self.inner.get(&id).map(|source| Arc::clone(&source))
57    }
58}