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
use crate::FileSystem;
use std::{fmt, path::PathBuf};

/// A identifier for a [crate::Source]
#[derive(PartialEq, Eq, Clone, Copy, Hash)]
#[cfg_attr(feature = "span-serialize", derive(serde::Serialize))]
pub struct SourceId(pub(crate) u16);

impl fmt::Debug for SourceId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!("SourceId({})", self.0))
    }
}

impl SourceId {
    /// Returns a [SourceId] handle that references a file and its content
    pub fn new(filesystem: &mut impl FileSystem, path: PathBuf, content: String) -> Self {
        filesystem.new_source_id(path, content)
    }

    /// For content which does not have a source file **use with caution**
    pub const NULL: Self = Self(0);

    pub const fn is_null(&self) -> bool {
        self.0 == 0
    }
}

#[cfg(feature = "self-rust-tokenize")]
pub const SPAN_TOKEN_IDENT: &str = "CURRENT_SOURCE_ID";

#[cfg(feature = "self-rust-tokenize")]
impl self_rust_tokenize::SelfRustTokenize for SourceId {
    fn append_to_token_stream(
        &self,
        token_stream: &mut self_rust_tokenize::proc_macro2::TokenStream,
    ) {
        let current_source_id_reference = self_rust_tokenize::proc_macro2::Ident::new(
            SPAN_TOKEN_IDENT,
            self_rust_tokenize::proc_macro2::Span::call_site(),
        );
        self_rust_tokenize::TokenStreamExt::append(token_stream, current_source_id_reference);
    }
}