datex_core/ast/error/
src.rs

1use internment::Intern;
2use std::{
3    fmt,
4    path::{Path, PathBuf},
5};
6
7#[derive(Copy, Clone, PartialEq, Eq, Hash)]
8pub struct SrcId(Intern<Vec<String>>);
9
10impl fmt::Display for SrcId {
11    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12        if self.0.is_empty() {
13            write!(f, "?")
14        } else {
15            write!(f, "{}", self.0.clone().join("/"))
16        }
17    }
18}
19
20impl fmt::Debug for SrcId {
21    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
22        write!(f, "{}", self)
23    }
24}
25
26impl SrcId {
27    #[cfg(test)]
28    pub fn empty() -> Self {
29        SrcId(Intern::new(Vec::new()))
30    }
31
32    pub fn repl() -> Self {
33        SrcId(Intern::new(vec!["repl".to_string()]))
34    }
35    pub fn test() -> Self {
36        SrcId(Intern::new(vec!["test".to_string()]))
37    }
38
39    pub fn from_path<P: AsRef<Path>>(path: P) -> Self {
40        SrcId(Intern::new(
41            path.as_ref()
42                .iter()
43                .map(|c| c.to_string_lossy().into_owned())
44                .collect(),
45        ))
46    }
47
48    pub fn to_path(&self) -> PathBuf {
49        self.0.iter().map(|e| e.to_string()).collect()
50    }
51}
52impl Default for SrcId {
53    fn default() -> Self {
54        SrcId(Intern::new(vec!["<unknown>".to_string()]))
55    }
56}
57impl From<&str> for SrcId {
58    fn from(s: &str) -> Self {
59        SrcId(Intern::new(vec![s.to_string()]))
60    }
61}
62impl From<String> for SrcId {
63    fn from(s: String) -> Self {
64        SrcId(Intern::new(vec![s]))
65    }
66}
67impl From<PathBuf> for SrcId {
68    fn from(s: PathBuf) -> Self {
69        SrcId::from_path(s)
70    }
71}