spade-common 0.20.0

Helper crate for https://spade-lang.org/
Documentation
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use serde::{Deserialize, Serialize};
use spade_codespan::{ByteOffset, Span};
use spade_codespan_reporting::diagnostic::Label;

pub trait AsLabel {
    fn file_id(&self) -> usize;
    fn span(&self) -> std::ops::Range<usize>;

    fn primary_label(&self) -> Label<usize> {
        Label::primary(self.file_id(), self.span())
    }

    fn secondary_label(&self) -> Label<usize> {
        Label::secondary(self.file_id(), self.span())
    }
}

pub type FullSpan = (Span, usize);

impl<T> From<&Loc<T>> for FullSpan {
    fn from(loc: &Loc<T>) -> Self {
        (loc.span, loc.file_id)
    }
}

impl<T> From<Loc<T>> for FullSpan {
    fn from(loc: Loc<T>) -> Self {
        FullSpan::from(&loc)
    }
}

impl AsLabel for FullSpan {
    fn span(&self) -> std::ops::Range<usize> {
        self.0.into()
    }

    fn file_id(&self) -> usize {
        self.1
    }
}

pub trait HasCodespan {
    fn codespan(&self) -> Span;
}

impl<T> HasCodespan for Loc<T> {
    fn codespan(&self) -> Span {
        self.span
    }
}

impl HasCodespan for Span {
    fn codespan(&self) -> Span {
        *self
    }
}

impl HasCodespan for std::ops::Range<usize> {
    fn codespan(&self) -> Span {
        lspan(self.clone())
    }
}

pub trait WithLocation: Sized {
    fn at(self, file_id: usize, span: &impl HasCodespan) -> Loc<Self>
    where
        Self: Sized,
    {
        Loc::new(self, span.codespan(), file_id)
    }

    /// Creates a new Loc from another Loc
    fn at_loc<T: Sized>(self, loc: &Loc<T>) -> Loc<Self> {
        Loc::new(self, loc.span, loc.file_id)
    }

    /// Creates a new Loc from another Loc, but with future internal tracking that this loc
    /// is imprecise and should not be shown to a user outside Diagnostic::bug. Currently,
    /// this is completely untracked, but something we can enable in the future
    fn near_loc<T: Sized>(self, loc: &Loc<T>) -> Loc<Self> {
        Loc::new(self, loc.span, loc.file_id)
    }

    fn between(
        self,
        file_id: usize,
        start: &impl HasCodespan,
        end: &impl HasCodespan,
    ) -> Loc<Self> {
        Loc::new(self, start.codespan().merge(end.codespan()), file_id)
    }

    fn between_locs<T, Y>(self, start: &Loc<T>, end: &Loc<Y>) -> Loc<Self> {
        assert!(start.file_id == end.file_id);
        Loc::new(self, start.codespan().merge(end.codespan()), end.file_id())
    }

    fn nowhere(self) -> Loc<Self>
    where
        Self: Sized,
    {
        self.at(0, &Span::new(0, 0))
    }
}

impl<T> WithLocation for T {}

pub fn lspan(s: logos::Span) -> Span {
    Span::new(s.start as u32, s.end as u32)
}

#[cfg(test)]
pub fn dummy() -> Span {
    Span::new(0, 0)
}

#[derive(Clone, Copy, Serialize, Deserialize)]
pub struct Loc<T> {
    pub inner: T,
    pub span: Span,
    pub file_id: usize,
}

impl<T> Loc<T> {
    #[inline(always)]
    pub fn new(inner: T, span: Span, file_id: usize) -> Self {
        Self {
            inner,
            span,
            file_id,
        }
    }
    #[inline(always)]
    pub fn nowhere(inner: T) -> Self {
        Self::new(inner, Span::new(0, 0), 0)
    }

    #[inline(always)]
    pub fn strip(self) -> T {
        self.inner
    }

    #[inline(always)]
    pub fn strip_ref(&self) -> &T {
        &self.inner
    }

    #[inline(always)]
    pub fn separate(self) -> (Self, Span) {
        let span = self.span;
        (self, span)
    }

    #[inline(always)]
    pub fn separate_loc(self) -> (Self, Loc<()>) {
        let loc = self.loc();
        (self, loc)
    }

    #[inline(always)]
    pub fn split(self) -> (T, Span) {
        (self.inner, self.span)
    }
    #[inline(always)]
    pub fn split_ref(&self) -> (&T, Span) {
        (&self.inner, self.span)
    }
    #[inline(always)]
    pub fn split_loc(self) -> (T, Loc<()>) {
        let loc = self.loc();
        (self.inner, loc)
    }
    #[inline(always)]
    pub fn split_loc_ref(&self) -> (&T, Loc<()>) {
        let loc = self.loc();
        (&self.inner, loc)
    }

    pub fn is_same_loc<R>(&self, other: &Loc<R>) -> bool {
        self.span == other.span && self.file_id == other.file_id
    }

    #[inline(always)]
    pub fn map<Y>(self, mut op: impl FnMut(T) -> Y) -> Loc<Y> {
        Loc {
            inner: op(self.inner),
            span: self.span,
            file_id: self.file_id,
        }
    }

    #[inline(always)]
    pub fn try_map<Y, E>(self, mut op: impl FnMut(T) -> Result<Y, E>) -> Result<Loc<Y>, E> {
        Ok(Loc {
            inner: op(self.inner)?,
            span: self.span,
            file_id: self.file_id,
        })
    }

    #[inline(always)]
    pub fn map_ref<Y>(&self, mut op: impl FnMut(&T) -> Y) -> Loc<Y> {
        Loc {
            inner: op(&self.inner),
            span: self.span,
            file_id: self.file_id,
        }
    }

    #[inline(always)]
    pub fn try_map_ref<Y, E>(&self, mut op: impl FnMut(&T) -> Result<Y, E>) -> Result<Loc<Y>, E> {
        Ok(Loc {
            inner: op(&self.inner)?,
            span: self.span,
            file_id: self.file_id,
        })
    }

    #[inline(always)]
    pub fn loc(&self) -> Loc<()> {
        Loc {
            inner: (),
            span: self.span,
            file_id: self.file_id,
        }
    }

    pub fn contains_start<R>(&self, other: &Loc<R>) -> bool {
        other.file_id == self.file_id
            && other.span.start() >= self.span.start()
            && other.span.start() < self.span.end()
    }

    /// Returns true if `self` ends before the start of `other`
    pub fn ends_before<R>(&self, other: &Loc<R>) -> bool {
        other.file_id == self.file_id && self.span.end() < other.span.start()
    }

    pub fn start_span(&self) -> Loc<()> {
        ().at(
            self.file_id,
            &Span::new(self.span.start(), self.span.start()),
        )
    }
    pub fn end_span(&self) -> Loc<()> {
        ().at(self.file_id, &Span::new(self.span.end(), self.span.end()))
    }

    /// Shrinks a Loc on the left size by the width of the specified string.
    /// For example (( abc ))
    ///             ^^^^^^^^^ .shrink_left("((")
    /// results in
    /// For example (( abc ))
    ///               ^^^^^^^
    ///
    /// Note that this is only valid if the loc actually points to the specified string,
    /// otherwise the behaviour is undefined
    ///
    /// If the span is empty, does nothing
    pub fn shrink_left(&self, s: &str) -> Loc<()> {
        if self.span.start() == self.span.end() {
            self.loc()
        } else {
            Loc {
                inner: (),
                span: Span::new(
                    self.span.start() + ByteOffset::from_str_len(s),
                    self.span.end(),
                ),
                file_id: self.file_id,
            }
        }
    }

    /// See [shrink_right]
    pub fn shrink_right(&self, s: &str) -> Loc<()> {
        if self.span.start() == self.span.end() {
            self.loc()
        } else {
            Loc {
                inner: (),
                span: Span::new(
                    self.span.start(),
                    self.span.end() - ByteOffset::from_str_len(s),
                ),
                file_id: self.file_id,
            }
        }
    }
}

impl<T, E> Loc<Result<T, E>> {
    pub fn map_err<E2>(self, err_fn: impl Fn(E, Loc<()>) -> E2) -> Result<Loc<T>, E2> {
        match self.inner {
            Ok(inner) => Ok(Loc {
                inner,
                span: self.span,
                file_id: self.file_id,
            }),
            Err(e) => Err(err_fn(e, ().at(self.file_id, &self.span))),
        }
    }
}

impl<T> Loc<Option<T>>
where
    T: WithLocation,
{
    pub fn transpose(self) -> Option<Loc<T>> {
        let loc = self.loc();
        match self.inner {
            Some(inner) => Some(inner.at_loc(&loc)),
            None => None,
        }
    }
}

impl<T> PartialEq for Loc<T>
where
    T: PartialEq,
{
    #[inline(always)]
    fn eq(&self, other: &Self) -> bool {
        self.inner == other.inner
    }
}

impl<T> Eq for Loc<T> where T: Eq {}

impl<T> PartialOrd for Loc<T>
where
    T: PartialOrd,
{
    #[inline(always)]
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.inner.partial_cmp(&other.inner)
    }
}

impl<T> Ord for Loc<T>
where
    T: Ord,
{
    #[inline(always)]
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.inner.cmp(&other.inner)
    }
}

impl<T> std::fmt::Display for Loc<T>
where
    T: std::fmt::Display,
{
    #[inline(always)]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.inner.fmt(f)
    }
}

impl<T> std::hash::Hash for Loc<T>
where
    T: std::hash::Hash,
{
    #[inline(always)]
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.inner.hash(state)
    }
}

impl<T> std::fmt::Debug for Loc<T>
where
    T: std::fmt::Debug,
{
    #[inline(always)]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.inner.fmt(f)
    }
}

impl<T> std::ops::Deref for Loc<T> {
    type Target = T;

    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}
impl<T> std::ops::DerefMut for Loc<T> {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

impl<T> AsLabel for Loc<T> {
    #[inline(always)]
    fn file_id(&self) -> usize {
        self.file_id
    }

    #[inline(always)]
    fn span(&self) -> std::ops::Range<usize> {
        self.span.into()
    }
}