-
Notifications
You must be signed in to change notification settings - Fork 891
/
location.rs
80 lines (68 loc) · 1.86 KB
/
location.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
use serde::{Deserialize, Serialize};
/// Sourcecode location.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Location {
pub(super) row: u32,
pub(super) column: u32,
}
impl Location {
pub fn fmt_with(
&self,
f: &mut std::fmt::Formatter,
e: &impl std::fmt::Display,
) -> std::fmt::Result {
write!(f, "{} at line {} column {}", e, self.row(), self.column())
}
}
impl Location {
/// Creates a new Location object at the given row and column.
///
/// # Example
/// ```
/// use rustpython_compiler_core::Location;
/// let loc = Location::new(10, 10);
/// ```
pub fn new(row: usize, column: usize) -> Self {
let row = row.try_into().expect("Location::row over u32");
let column = column.try_into().expect("Location::column over u32");
Location { row, column }
}
/// Current row
pub fn row(&self) -> usize {
self.row as usize
}
/// Current column
pub fn column(&self) -> usize {
self.column as usize
}
pub fn reset(&mut self) {
self.row = 1;
self.column = 0;
}
pub fn go_right(&mut self) {
self.column += 1;
}
pub fn go_left(&mut self) {
self.column -= 1;
}
pub fn newline(&mut self) {
self.row += 1;
self.column = 1;
}
}
#[cfg(test)]
mod tests {
use crate::Location;
#[test]
fn test_gt() {
assert!(Location::new(1, 2) > Location::new(1, 1));
assert!(Location::new(2, 1) > Location::new(1, 1));
assert!(Location::new(2, 1) > Location::new(1, 2));
}
#[test]
fn test_lt() {
assert!(Location::new(1, 1) < Location::new(1, 2));
assert!(Location::new(1, 1) < Location::new(2, 1));
assert!(Location::new(1, 2) < Location::new(2, 1));
}
}