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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
use rustre_parser::ast::{AstToken, IdNode, IdRefNode, Ident};
use std::borrow::Cow;
use std::convert::Infallible;
use std::fmt::{Debug, Display, Formatter};
use std::str::FromStr;

/// Name of a node, param, variable, type, package, model, etc., as it appears in the declaration
///
/// This is simply a cheap newtype around `String`.
///
/// # Example values
///
///   * Nodes: `sin`, `adder`, `map`
///   * Variables: `a`, `b`, `cin`
///   * Types: `state`
///   * Packages: `Lustre`
///
/// # Usage
///
/// [Id]s do not remember their source span. Therefore, queries that rely on it may want to require
/// both to be given, or to compute the [Id] inside them. [Id]s without an accompanying span should
/// only be used as inputs to query that don't report the errors themselves.
#[derive(Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Id(str);

impl Id {
    pub const LUSTRE_PACKAGE: &'static Self = Id::from_str("Lustre");

    pub const fn from_str(str: &str) -> &Self {
        unsafe { std::mem::transmute(str) }
    }
}

impl<'a> Default for &'a Id {
    fn default() -> Self {
        Id::from_str("")
    }
}

impl Default for Box<Id> {
    fn default() -> Self {
        <&Id>::default().to_owned()
    }
}

impl Clone for Box<Id> {
    fn clone(&self) -> Self {
        self.as_ref().to_owned()
    }
}

impl<'a> From<&'a str> for &'a Id {
    fn from(value: &'a str) -> Self {
        Id::from_str(value)
    }
}

impl From<Box<str>> for Box<Id> {
    fn from(value: Box<str>) -> Self {
        unsafe { std::mem::transmute(value) }
    }
}

impl From<String> for Box<Id> {
    fn from(value: String) -> Self {
        Self::from(value.into_boxed_str())
    }
}

impl<'a> From<&'a Id> for Cow<'a, Id> {
    fn from(value: &'a Id) -> Self {
        Self::Borrowed(value)
    }
}

impl<'a> From<Box<Id>> for Cow<'a, Id> {
    fn from(value: Box<Id>) -> Self {
        Self::Owned(value)
    }
}

impl ToOwned for Id {
    type Owned = Box<Id>;

    fn to_owned(&self) -> Self::Owned {
        let box_str = String::from(&self.0).into_boxed_str();
        Box::<Id>::from(box_str)
    }
}

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

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

/// Reference to a node, param, variable, type, package, model, etc., as it appears in the
/// usage / call site
///
/// This _may_ be identical to an [`Id`], but can also be preceded by a package name
/// (`package::member`).
///
/// # Example values
///
///   * Implicit packages (equivalent to simple [Id]s): `sin`, `a`, `state`
///   * Explicit package: `Lustre::add`, `Alu::shift_right`
///
/// # Usage
///
/// Like [`Id`]s, [IdRef]s don't store their source span. The [same tips][Id#usage] apply.
///
/// # Name resolution semantics
///
///   * If an [IdRef] has an explicit package name, the resolution is trivial
///   * If an [IdRef] has no explicit package name, IDs are first resolved in the current scope
///     (local or package), and then in the `Lustre::` package
#[derive(Clone, Hash, PartialEq)]
pub struct IdRef<'p, 'm> {
    package: Option<Cow<'p, Id>>,
    member: Cow<'m, Id>,
}

impl<'p, 'm> IdRef<'p, 'm> {
    pub fn new(package: Option<impl Into<Cow<'p, Id>>>, member: impl Into<Cow<'m, Id>>) -> Self {
        Self {
            package: package.map(|p| p.into()),
            member: member.into(),
        }
    }

    /// Creates an [IdRef] with an implicit (absent) package name
    pub fn new_implicit(member: impl Into<Cow<'m, Id>>) -> Self {
        Self {
            package: None,
            member: member.into(),
        }
    }

    /// Creates an [IdRef] with `Lustre::` for a package name
    pub fn new_lustre(member: impl Into<Cow<'m, Id>>) -> Self {
        Self {
            package: Some(Id::LUSTRE_PACKAGE.into()),
            member: member.into(),
        }
    }

    pub fn as_package(&self) -> Option<&Id> {
        self.package.as_deref()
    }

    pub fn as_member(&self) -> &Id {
        self.member.as_ref()
    }

    /// Retrieves the member, only if this IdRef has no explicit package
    ///
    /// Can be used to attempt local resolution of an identifier, which only makes sense when no
    /// package is specified.
    pub fn as_member_implicit(&self) -> Option<&Id> {
        Some(self.member.as_ref()).filter(|_| self.package.is_none())
    }

    pub fn member_eq(&self, other: &Id) -> bool {
        self.member.as_ref() == other
    }

    pub fn into_inner(self) -> (Option<Cow<'p, Id>>, Cow<'m, Id>) {
        (self.package, self.member)
    }
}

/// Converts the [`Id`] to an [`IdRef`] using [`IdRef::new_implicit`]
impl<'p, 'm> From<&'m Id> for IdRef<'p, 'm> {
    fn from(value: &'m Id) -> Self {
        Self::new_implicit(value)
    }
}

impl<'p, 'm> Display for IdRef<'p, 'm> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self.package.as_deref() {
            Some(package) => write!(f, "{}::{}", &package.0, &self.member.0),
            None => write!(f, "{}", &self.member),
        }
    }
}

impl<'p, 'm> Debug for IdRef<'p, 'm> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self.package.as_deref() {
            Some(package) => write!(f, "`{}::{}`", &package.0, &self.member.0),
            None => write!(f, "{:?}", &self.member),
        }
    }
}

/// Parses an IdRef from a &str
///
/// Most of the time, the actual Rustre parser will be used instead of this function. It exists
/// mostly for convenience and interoperability. Please note that this implementation is infallible,
/// and won't check for invalid chars in identifiers.
impl<'p, 'm> FromStr for IdRef<'p, 'm> {
    type Err = Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s.rsplit_once("::") {
            Some((package, model)) => Self::new(
                Some(Id::from_str(package).to_owned()),
                Id::from_str(model).to_owned(),
            ),
            None => Self::new_implicit(Id::from_str(s).to_owned()),
        })
    }
}

// AST glue

impl<'a> From<&'a Ident> for &'a Id {
    fn from(value: &'a Ident) -> Self {
        Id::from_str(value.text())
    }
}

impl<'a> From<&'a Ident> for Box<Id> {
    fn from(value: &'a Ident) -> Self {
        Id::from_str(value.text()).to_owned()
    }
}

impl From<Ident> for Box<Id> {
    fn from(value: Ident) -> Self {
        (&value).into()
    }
}

impl<'a> From<&'a IdNode> for Box<Id> {
    fn from(value: &'a IdNode) -> Self {
        let ident = value.ident().expect("unparseable");
        ident.into()
    }
}

impl From<IdNode> for Box<Id> {
    fn from(value: IdNode) -> Self {
        (&value).into()
    }
}

impl<'p, 'm> From<&IdRefNode> for IdRef<'p, 'm> {
    fn from(value: &IdRefNode) -> Self {
        let package = value.package().map(<Box<Id>>::from);
        let member = <Box<Id>>::from(value.member());
        Self::new(package, member)
    }
}

impl<'p, 'm> From<IdRefNode> for IdRef<'p, 'm> {
    fn from(value: IdRefNode) -> Self {
        (&value).into()
    }
}