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
//! Source code locations (borrowed from rustc's [libsyntax_pos])
//!
//! [libsyntax_pos]: https://github.com/rust-lang/rust/blob/master/src/libsyntax_pos/lib.rs

use std::cmp::{self, Ordering};
use std::fmt;
use std::ops::{Add, AddAssign, Sub, SubAssign};

macro_rules! pos_struct {
    (#[$doc:meta] pub struct $Pos:ident($T:ty);) => {
        #[$doc]
        #[derive(Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
        #[cfg_attr(feature = "serde_derive", derive(Serialize, Deserialize))]
        pub struct $Pos($T);

        impl fmt::Debug for $Pos {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                write!(f, "{}", self.0)
            }
        }

        impl $Pos {
            pub fn to_usize(&self) -> usize {
                self.0 as usize
            }
        }

        impl From<usize> for $Pos {
            fn from(src: usize) -> $Pos {
                $Pos(src as $T)
            }
        }

        impl Add for $Pos {
            type Output = $Pos;

            fn add(self, rhs: $Pos) -> $Pos {
                $Pos::from(self.to_usize() + rhs.to_usize())
            }
        }

        impl AddAssign for $Pos {
            fn add_assign(&mut self, rhs: $Pos) {
                self.0 += rhs.0;
            }
        }

        impl Sub for $Pos {
            type Output = $Pos;

            fn sub(self, rhs: $Pos) -> $Pos {
                $Pos::from(self.to_usize() - rhs.to_usize())
            }
        }

        impl SubAssign for $Pos {
            fn sub_assign(&mut self, rhs: $Pos) {
                self.0 -= rhs.0;
            }
        }
    };
}

pos_struct! {
    /// A byte offset in a source string
    pub struct BytePos(u32);
}

impl fmt::Display for BytePos {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

pos_struct! {
    /// A `0`-indexed column number, displayed externally as if it were offset from `1`.
    pub struct Column(u32);
}

impl fmt::Display for Column {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        (self.0 + 1).fmt(f)
    }
}

pos_struct! {
    /// A `0`-indexed line number, displayed externally as if it were offset from `1`.
    pub struct Line(u32);
}

impl fmt::Display for Line {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        (self.0 + 1).fmt(f)
    }
}

/// A location in a source file
#[derive(Copy, Clone, Default, Eq, PartialEq, Debug, Hash, Ord, PartialOrd)]
pub struct Location {
    pub line: Line,
    pub column: Column,
    pub absolute: BytePos,
}

impl Location {
    pub fn shift(mut self, ch: char) -> Location {
        if ch == '\n' {
            self.line += Line::from(1);
            self.column = Column::from(0);
        } else {
            self.column += Column::from(1);
        }
        self.absolute += BytePos::from(ch.len_utf8());
        self
    }
}

impl fmt::Display for Location {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Line: {}, Column: {}", self.line, self.column)
    }
}

/// An expansion identifier tracks wheter a span originated from a macro expansion or not
#[derive(Copy, Clone, Default, Ord, PartialOrd, Eq, PartialEq, Debug)]
pub struct ExpansionId(pub u32);

pub const NO_EXPANSION: ExpansionId = ExpansionId(0);

pub const UNKNOWN_EXPANSION: ExpansionId = ExpansionId(1);

/// A span between two locations in a source file
#[derive(Copy, Clone, Default, Eq, Debug)]
pub struct Span<Pos> {
    pub start: Pos,
    pub end: Pos,
    pub expansion_id: ExpansionId,
}

impl<Pos> PartialEq for Span<Pos>
where
    Pos: PartialEq,
{
    fn eq(&self, other: &Span<Pos>) -> bool {
        self.start == other.start && self.end == other.end
    }
}

impl<Pos> PartialOrd for Span<Pos>
where
    Pos: PartialOrd,
{
    fn partial_cmp(&self, other: &Span<Pos>) -> Option<Ordering> {
        self.start
            .partial_cmp(&other.start)
            .and_then(|ord| if ord == Ordering::Equal {
                self.end.partial_cmp(&self.end)
            } else {
                Some(ord)
            })
    }
}

impl<Pos> Ord for Span<Pos>
where
    Pos: Ord,
{
    fn cmp(&self, other: &Span<Pos>) -> Ordering {
        let ord = self.start.cmp(&other.start);
        if ord == Ordering::Equal {
            self.end.cmp(&self.end)
        } else {
            ord
        }
    }
}


impl<Pos: Ord> Span<Pos> {
    pub fn new(start: Pos, end: Pos) -> Span<Pos> {
        Span::with_id(start, end, NO_EXPANSION)
    }

    pub fn with_id(start: Pos, end: Pos, no_expansion: ExpansionId) -> Span<Pos> {
        Span {
            start: start,
            end: end,
            expansion_id: no_expansion,
        }
    }

    pub fn contains(self, other: Span<Pos>) -> bool {
        self.start <= other.start && other.end <= self.end
    }

    pub fn containment(self, pos: &Pos) -> Ordering {
        use std::cmp::Ordering::*;

        match (pos.cmp(&self.start), pos.cmp(&self.end)) {
            (Equal, _) | (_, Equal) | (Greater, Less) => Equal,
            (Less, _) => Less,
            (_, Greater) => Greater,
        }
    }

    pub fn containment_exclusive(self, pos: &Pos) -> Ordering {
        if self.end == *pos {
            Ordering::Greater
        } else {
            self.containment(pos)
        }
    }

    pub fn merge(self, other: Span<Pos>) -> Option<Span<Pos>> {
        assert!(self.expansion_id == other.expansion_id);
        if (self.start <= other.start && self.end > other.start) ||
            (self.start >= other.start && self.start < other.end)
        {
            Some(Span {
                start: cmp::min(self.start, other.start),
                end: cmp::max(self.end, other.end),
                expansion_id: self.expansion_id,
            })
        } else {
            None
        }
    }

    pub fn map<Pos2, F>(self, mut f: F) -> Span<Pos2>
    where
        F: FnMut(Pos) -> Pos2,
    {
        Span {
            start: f(self.start),
            end: f(self.end),
            expansion_id: self.expansion_id,
        }
    }
}

#[derive(Copy, Clone, Debug, Eq)]
pub struct Spanned<T, Pos> {
    pub span: Span<Pos>,
    pub value: T,
}

impl<T, Pos> Spanned<T, Pos> {
    pub fn map<U, F>(self, mut f: F) -> Spanned<U, Pos>
    where
        F: FnMut(T) -> U,
    {
        Spanned {
            span: self.span,
            value: f(self.value),
        }
    }
}

impl<T: PartialEq, Pos> PartialEq for Spanned<T, Pos> {
    fn eq(&self, other: &Spanned<T, Pos>) -> bool {
        self.value == other.value
    }
}

impl<T: fmt::Display, Pos: fmt::Display> fmt::Display for Spanned<T, Pos> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}: {}", self.span.start, self.value)
    }
}

pub fn span<Pos>(start: Pos, end: Pos) -> Span<Pos> {
    Span {
        start: start,
        end: end,
        expansion_id: NO_EXPANSION,
    }
}

pub fn spanned<T, Pos>(span: Span<Pos>, value: T) -> Spanned<T, Pos> {
    Spanned {
        span: span,
        value: value,
    }
}

pub fn spanned2<T, Pos>(start: Pos, end: Pos, value: T) -> Spanned<T, Pos> {
    Spanned {
        span: span(start, end),
        value: value,
    }
}

pub trait HasSpan {
    fn span(&self) -> Span<BytePos>;
}