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
//! # Location
//!
//! Data to locate span of text, in files.
//! The main struct is [`Location`].

use std::{path::Path, rc::Rc};

use fragile::Fragile;

/// # Summary
///
/// Information about a position in a file,
/// stored as `(line, char_position)`
///
/// # Example
///
/// ```text
/// abc def
/// ghi
/// ```
///
/// Here, the `Location` of `a` is `(0, 0)`,
/// and the one of `i` is `(1, 2)`.
pub type Location = (usize, usize);

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn location() {
        let input: Rc<str>= Rc::from(
            "01234
56789abcdef",
        );
	let lines: Rc<[usize]> = vec![
	    0,
	    6
	].into();
        let span = Span::new(
            Path::new("a cool filename"),
            (0, 3),
            (1, 6),
            3,
            11,
            input.clone(),
	    lines.clone(),
        );
        assert_eq!(&*span.file(), Path::new("a cool filename"));
        assert_eq!(span.start(), (0, 3));
        assert_eq!(span.end(), (1, 6));
        assert_eq!(span.start_byte(), 3);
        assert_eq!(span.end_byte(), 11);
	assert_eq!(span.text(), &*input);
	assert_eq!(span.lines(), &*lines);
        let span = Span::new(
	    Path::new(""),
	    (0, 0),
	    (0, 0),
	    0,
	    0,
	    input.clone(),
	    lines.clone(),
	);
        assert_eq!(&*span.file(), Path::new(""));
        assert_eq!(span.start(), (0, 0));
        assert_eq!(span.end(), (0, 0));
        assert_eq!(span.start_byte(), 0);
        assert_eq!(span.end_byte(), 0);
	assert_eq!(span.text(), &*input);
	assert_eq!(span.lines(), &*lines);
    }

    #[test]
    #[should_panic]
    fn wrong_location() {
        Span::new(Path::new("some file"), (1, 0), (0, 0), 1, 0, "", Vec::new());
    }
    #[test]
    #[should_panic]
    fn wrong_location2() {
        Span::new(Path::new("some file"), (1, 5), (1, 3), 8, 6, "", Vec::new());
    }
}

/// # Summary
///
/// Stores the location of any bit of information that is bound to a file.
/// Asks a start position (inclusive) and an end position (inclusive).
/// This means that if my chunk of data is one character long,
/// and starts at the beginning of the file `myfile`, the location
/// data bound to it is the one defined in example 1.
///
/// # Examples
///
/// Example 1
///
/// ```rust
/// # use beans::span::Span;
/// # use std::path::Path;
/// let span = Span::new(
///     Path::new("myfile"),
///     (0, 0),
///     (0, 0),
///     0,
///     0,
///     "a",
///     vec![0],
/// );
/// ```
///
/// Example 2 -- `afile`
///
/// ```text
/// abc def
/// ghi
/// ```
///
/// Here, the location of `c def/gh` is
///
/// ```rust
/// # use beans::span::Span;
/// # use std::path::Path;
/// Span::new(
///   Path::new("afile"),
///   (0, 4),
///   (1, 2),
///   4,
///   8,
///   "abcde\nbel",
///   vec![0, 6],
/// )
/// # ;
/// ```
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Span {
    file: Rc<Path>,
    start: Location,
    end: Location,
    start_byte: usize,
    end_byte: usize,
    text: Rc<str>,
    lines: Rc<[usize]>,
}

impl std::fmt::Display for Span {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "in file {}, ", self.file.display())?;
        if self.start.0 == self.end.0 {
            if self.start.1 + 1 == self.end.1 {
                write!(
                    f,
                    "at character {} of line {}",
                    self.start.1,
                    self.start.0 + 1,
                )
            } else {
                write!(
                    f,
                    "at characters {}-{} of line {}",
                    self.start.1,
                    self.end.1.checked_sub(1).unwrap_or_default(),
                    self.start.0 + 1,
                )
            }
        } else {
            write!(
                f,
                "from character {} of line {} to character {} of line {}",
                self.start.1,
                self.start.0 + 1,
                self.end.1.checked_sub(1).unwrap_or_default(),
                self.end.0 + 1,
            )
        }
    }
}

impl Span {
    /// Create a new `Location` object.
    /// Require three arguments,
    ///  * file: the name of the file where the data is;
    ///  * start: the location (inclusive) of the beginning of the data;
    ///  * end: the location (exclusive) of the end of the data.
    ///
    /// Panic if start > end (lexicographic order)
    pub fn new(
        file: impl Into<Rc<Path>>,
        start: Location,
        end: Location,
        start_byte: usize,
        end_byte: usize,
        text: impl Into<Rc<str>>,
	lines: impl Into<Rc<[usize]>>,
    ) -> Self {
        assert!(start.0 < end.0 || (start.0 == end.0 && start.1 <= end.1)); // TODO: remove assert and add proper error handling.
        let file = file.into();
        let text = text.into();
	let lines = lines.into();
        Self {
            file,
            start,
            end,
            start_byte,
            end_byte,
            text,
	    lines,
        }
    }

    pub fn sup(&self, other: &Self) -> Self {
        Self {
            file: self.file.clone(),
            start_byte: self.start_byte.min(other.start_byte),
            end_byte: self.end_byte.max(other.end_byte),
            start: self.start.min(other.start),
            end: self.end.max(other.end),
            text: self.text.clone(),
	    lines: self.lines.clone(),
        }
    }

    /// Returns the file from which the data is taken.
    pub fn file(&self) -> Rc<Path> {
        self.file.clone()
    }

    /// Returns the location of the beginning of the chunk of data in the file.
    pub fn start(&self) -> Location {
        self.start
    }

    /// Returns the location of the end of the chunk of data in the file
    pub fn end(&self) -> Location {
        self.end
    }

    pub fn start_byte(&self) -> usize {
        self.start_byte
    }

    pub fn end_byte(&self) -> usize {
        self.end_byte
    }

    /// Returns (start, end), where the line `line_number` is
    /// `self.text()[start..end]`
    pub fn line_bytes_of_line(&self, line_number: usize) -> (usize, usize) {
	let start = self.lines[line_number];
	let end = if line_number+1 == self.lines.len() {
	    self.text.len()
	} else {
	    self.lines[line_number+1]
	};
	(start, end)
    }
    
    pub fn text(&self) -> &str {
	&self.text
    }

    pub fn lines(&self) -> &[usize] {
	&self.lines
    }
}

impl From<&Span> for Fragile<Span> {
    fn from(location: &Span) -> Fragile<Span> {
        Fragile::new(location.clone())
    }
}