lang_interpreter/lexer/
code_position.rs1use std::cmp::Ordering;
2use std::fmt::{Display, Formatter};
3
4#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
5pub struct CodePosition {
6 line_number_from: isize,
7 line_number_to: isize,
8 column_from: isize,
9 column_to: isize,
10}
11
12impl CodePosition {
13 pub const EMPTY: CodePosition = CodePosition {
14 line_number_from: -1, line_number_to: -1, column_from: -1, column_to: -1,
15 };
16
17 pub fn new(line_number_from: isize, line_number_to: isize, column_from: isize, column_to: isize) -> Self {
18 Self { line_number_from, line_number_to, column_from, column_to }
19 }
20
21 #[must_use]
22 pub fn combine(&self, code_position: &CodePosition) -> CodePosition {
23 if *self == Self::EMPTY || *code_position == Self::EMPTY {
24 return Self::EMPTY;
25 }
26
27 let column_from = match self.line_number_from.cmp(&code_position.line_number_from) {
28 Ordering::Equal => self.column_from.min(code_position.column_from),
29 Ordering::Less => self.column_from,
30 Ordering::Greater => code_position.column_from,
31 };
32
33 let column_to = match self.line_number_to.cmp(&code_position.line_number_to) {
34 Ordering::Equal => self.column_to.max(code_position.column_to),
35 Ordering::Greater => self.column_to,
36 Ordering::Less => code_position.column_to,
37 };
38
39 Self::new(
40 self.line_number_from.min(code_position.line_number_from),
41 self.line_number_to.min(code_position.line_number_to),
42 column_from,
43 column_to,
44 )
45 }
46
47 pub fn to_compact_string(&self) -> String {
48 format!(
49 "{}:{}-{}:{}",
50 self.line_number_from, self.column_from,
51
52 self.line_number_to, self.column_to,
53 )
54 }
55
56 pub fn line_number_from(&self) -> isize {
57 self.line_number_from
58 }
59
60 pub fn line_number_to(&self) -> isize {
61 self.line_number_to
62 }
63
64 pub fn column_from(&self) -> isize {
65 self.column_from
66 }
67
68 pub fn column_to(&self) -> isize {
69 self.column_to
70 }
71}
72
73impl Display for CodePosition {
74 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
75 write!(
76 f, "{:5}:{:3} - {:5}:{:3}",
77 self.line_number_from, self.column_from,
78
79 self.line_number_to, self.column_to,
80 )
81 }
82}