spade_common/
name.rs

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
use serde::{Deserialize, Serialize};

use crate::location_info::{Loc, WithLocation};

#[derive(PartialEq, Debug, Clone, Eq, Hash, Serialize, Deserialize)]
pub struct Identifier(pub String);

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

impl WithLocation for Identifier {}

#[derive(PartialEq, Debug, Clone, Eq, Hash, Serialize, Deserialize)]
pub struct Path(pub Vec<Loc<Identifier>>);
impl WithLocation for Path {}

impl Path {
    pub fn as_strs(&self) -> Vec<&str> {
        self.0.iter().map(|id| id.inner.0.as_ref()).collect()
    }
    pub fn as_strings(&self) -> Vec<String> {
        self.0.iter().map(|id| id.inner.0.clone()).collect()
    }
    /// Generate a path from a list of strings
    pub fn from_strs(elems: &[&str]) -> Self {
        Path(
            elems
                .iter()
                .map(|x| Identifier(x.to_string()).nowhere())
                .collect(),
        )
    }

    pub fn ident(ident: Loc<Identifier>) -> Self {
        Self(vec![ident])
    }

    pub fn push_ident(&self, ident: Loc<Identifier>) -> Path {
        let mut result = self.clone();
        result.0.push(ident);
        result
    }

    pub fn pop(&self) -> Self {
        let mut result = self.clone();
        result.0.pop().expect("Failed to pop identifier from path");
        result
    }

    pub fn join(&self, other: Path) -> Path {
        let mut result = self.clone();
        for ident in other.0 {
            result = result.push_ident(ident);
        }
        result
    }

    /// If the path is lib::<rest> return Some(<rest>), else None
    pub fn lib_relative(&self) -> Option<Path> {
        if self.0.first() == Some(&Identifier("lib".to_string()).nowhere()) {
            Some(Path(Vec::from(&self.0[1..])))
        } else {
            None
        }
    }

    /// The last element of the path. Panics if the path is empty
    pub fn tail(&self) -> Identifier {
        self.0
            .last()
            .expect("Tried getting tail of empty path")
            .inner
            .clone()
    }

    /// Returns the whole path apart from the tail. Panics if the path is empty
    pub fn prelude(&self) -> Path {
        Self(self.0[0..self.0.len() - 1].to_owned())
    }
}

impl std::fmt::Display for Path {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_strs().join("::"))
    }
}

/// Anything named will get assigned a unique name ID during AST lowering in order to avoid caring
/// about scopes once HIR has been generated. This is the type of those IDs
///
/// The associated string is only used for formatting when printing. The hash and eq methods do not
/// use it
#[derive(Clone, Serialize, Deserialize)]
pub struct NameID(pub u64, pub Path);
impl WithLocation for NameID {}

impl std::cmp::PartialEq for NameID {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl std::cmp::Eq for NameID {}

impl std::cmp::PartialOrd for NameID {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.0.cmp(&other.0))
    }
}

impl std::cmp::Ord for NameID {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.0.cmp(&other.0)
    }
}

impl std::hash::Hash for NameID {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.0.hash(state);
    }
}

impl std::fmt::Debug for NameID {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}#{}", self.1, self.0)
    }
}
impl std::fmt::Display for NameID {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.1)
    }
}

pub mod testutil {
    use super::*;
    pub fn name_id(id: u64, name: &str) -> Loc<NameID> {
        NameID(id, Path::from_strs(&[name])).nowhere()
    }

    /// Shorthand for creating a name_id with static strs as name
    pub fn name_id_p(id: u64, name: &[&str]) -> Loc<NameID> {
        NameID(id, Path::from_strs(name)).nowhere()
    }
}