Skip to main content

runic_diagnostics/source/
line_column.rs

1/// One-based human-readable source coordinates.
2#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
3pub struct LineColumn {
4    line: LineNumber,
5    column: ColumnNumber,
6}
7
8impl LineColumn {
9    pub fn new(line: u32, column: u32) -> Option<Self> {
10        let line = LineNumber::new(line)?;
11        let column = ColumnNumber::new(column)?;
12        Some(Self { line, column })
13    }
14
15    pub const fn new_unchecked(line: LineNumber, column: ColumnNumber) -> Self {
16        Self { line, column }
17    }
18
19    pub const fn line(self) -> LineNumber {
20        self.line
21    }
22
23    pub const fn column(self) -> ColumnNumber {
24        self.column
25    }
26
27    pub const fn line_index(self) -> LineIndex {
28        self.line.to_index()
29    }
30
31    pub const fn column_index(self) -> ColumnIndex {
32        self.column.to_index()
33    }
34}
35
36macro_rules! declare_dual_number_and_index_type {
37    ($name:ident, $description:literal) => {
38        paste::paste! {
39            declare_dual_number_and_index_type!([<$name Index>], [<$name Number>], $description);
40        }
41    };
42
43    ($index_name:ident, $number_name:ident, $description:literal) => {
44        #[doc = concat!("A zero-indexed ", $description, " number")]
45        #[derive(Default, Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
46        #[cfg_attr(
47            feature = "zerocopy",
48            derive(
49                zerocopy::FromBytes,
50                zerocopy::Immutable,
51                zerocopy::IntoBytes,
52                zerocopy::KnownLayout,
53            )
54        )]
55        pub struct $index_name(pub u32);
56
57        impl $index_name {
58            #[doc = concat!("Convert to a [", stringify!($number_name), "]")]
59            pub const fn number(self) -> $number_name {
60                let number = self
61                    .0
62                    .checked_add(1)
63                    .expect("line or column index exceeds the representable one-based range");
64                $number_name(
65                    ::core::num::NonZeroU32::new(number)
66                        .expect("a checked one-based index is non-zero"),
67                )
68            }
69
70            /// Get the raw index value as a usize
71            #[inline(always)]
72            pub const fn to_usize(self) -> usize {
73                self.0 as usize
74            }
75
76            /// Get the raw index value as a u32
77            #[inline(always)]
78            pub const fn to_u32(self) -> u32 {
79                self.0
80            }
81
82            /// Add `offset` to this index, returning `None` on overflow
83            pub fn checked_add(self, offset: u32) -> Option<Self> {
84                self.0.checked_add(offset).map(Self)
85            }
86
87            /// Add a signed `offset` to this index, returning `None` on overflow
88            pub fn checked_add_signed(self, offset: i32) -> Option<Self> {
89                self.0.checked_add_signed(offset).map(Self)
90            }
91
92            /// Subtract `offset` from this index, returning `None` on underflow
93            pub fn checked_sub(self, offset: u32) -> Option<Self> {
94                self.0.checked_sub(offset).map(Self)
95            }
96
97            /// Add `offset` to this index, saturating to `u32::MAX` on overflow
98            pub const fn saturating_add(self, offset: u32) -> Self {
99                Self(self.0.saturating_add(offset))
100            }
101
102            /// Add a signed `offset` to this index, saturating to `0` on underflow, and `u32::MAX`
103            /// on overflow.
104            pub const fn saturating_add_signed(self, offset: i32) -> Self {
105                Self(self.0.saturating_add_signed(offset))
106            }
107
108            /// Subtract `offset` from this index, saturating to `0` on overflow
109            pub const fn saturating_sub(self, offset: u32) -> Self {
110                Self(self.0.saturating_sub(offset))
111            }
112        }
113
114        impl From<u32> for $index_name {
115            #[inline]
116            fn from(index: u32) -> Self {
117                Self(index)
118            }
119        }
120
121        impl From<$number_name> for $index_name {
122            #[inline]
123            fn from(index: $number_name) -> Self {
124                Self(index.to_u32() - 1)
125            }
126        }
127
128        impl ::core::ops::Add<u32> for $index_name {
129            type Output = Self;
130
131            #[inline]
132            fn add(self, rhs: u32) -> Self {
133                Self(self.0 + rhs)
134            }
135        }
136
137        impl ::core::ops::AddAssign<u32> for $index_name {
138            fn add_assign(&mut self, rhs: u32) {
139                let result = *self + rhs;
140                *self = result;
141            }
142        }
143
144        impl ::core::ops::Add<i32> for $index_name {
145            type Output = Self;
146
147            fn add(self, rhs: i32) -> Self {
148                self.checked_add_signed(rhs).expect("invalid offset: overflow occurred")
149            }
150        }
151
152        impl ::core::ops::AddAssign<i32> for $index_name {
153            fn add_assign(&mut self, rhs: i32) {
154                let result = *self + rhs;
155                *self = result;
156            }
157        }
158
159        impl ::core::ops::Sub<u32> for $index_name {
160            type Output = Self;
161
162            #[inline]
163            fn sub(self, rhs: u32) -> Self {
164                Self(self.0 - rhs)
165            }
166        }
167
168        impl ::core::ops::SubAssign<u32> for $index_name {
169            fn sub_assign(&mut self, rhs: u32) {
170                let result = *self - rhs;
171                *self = result;
172            }
173        }
174
175        impl ::core::fmt::Display for $index_name {
176            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
177                ::core::fmt::Display::fmt(&self.0, f)
178            }
179        }
180
181        #[cfg(feature = "arbitrary")]
182        impl ::proptest::prelude::Arbitrary for $index_name {
183            type Parameters = ();
184            type Strategy = ::proptest::prelude::BoxedStrategy<Self>;
185
186            fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
187                use ::proptest::prelude::*;
188                any::<u32>().prop_map(Self).boxed()
189            }
190        }
191
192        #[doc = concat!("A one-indexed ", $description, " number")]
193        #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
194        #[cfg_attr(
195            feature = "zerocopy",
196            derive(
197                zerocopy::Immutable,
198                zerocopy::IntoBytes,
199                zerocopy::KnownLayout,
200                zerocopy::TryFromBytes,
201            )
202        )]
203        pub struct $number_name(::core::num::NonZeroU32);
204
205        impl Default for $number_name {
206            fn default() -> Self {
207                #[allow(unsafe_code)]
208                Self(unsafe { ::core::num::NonZeroU32::new_unchecked(1) })
209            }
210        }
211
212        impl $number_name {
213            pub const fn new(number: u32) -> Option<Self> {
214                match ::core::num::NonZeroU32::new(number) {
215                    Some(num) => Some(Self(num)),
216                    None => None,
217                }
218            }
219
220            #[doc = concat!("Convert to a [", stringify!($index_name), "]")]
221            pub const fn to_index(self) -> $index_name {
222                $index_name(self.to_u32().saturating_sub(1))
223            }
224
225            /// Get the raw value as a usize
226            #[inline(always)]
227            pub const fn to_usize(self) -> usize {
228                self.0.get() as usize
229            }
230
231            /// Get the raw value as a u32
232            #[inline(always)]
233            pub const fn to_u32(self) -> u32 {
234                self.0.get()
235            }
236
237            /// Add `offset` to this index, returning `None` on overflow
238            pub fn checked_add(self, offset: u32) -> Option<Self> {
239                self.0.checked_add(offset).map(Self)
240            }
241
242            /// Add a signed `offset` to this index, returning `None` on overflow
243            pub fn checked_add_signed(self, offset: i32) -> Option<Self> {
244                self.0.get().checked_add_signed(offset).and_then(Self::new)
245            }
246
247            /// Subtract `offset` from this index, returning `None` on underflow
248            pub fn checked_sub(self, offset: u32) -> Option<Self> {
249                self.0.get().checked_sub(offset).and_then(Self::new)
250            }
251
252            /// Add `offset` to this index, saturating to `u32::MAX` on overflow
253            pub const fn saturating_add(self, offset: u32) -> Self {
254                #[allow(unsafe_code)]
255                Self(unsafe {
256                    ::core::num::NonZeroU32::new_unchecked(self.0.get().saturating_add(offset))
257                })
258            }
259
260            /// Add a signed `offset` to this index, saturating to `0` on underflow, and `u32::MAX`
261            /// on overflow.
262            pub fn saturating_add_signed(self, offset: i32) -> Self {
263                Self::new(self.to_u32().saturating_add_signed(offset)).unwrap_or_default()
264            }
265
266            /// Subtract `offset` from this index, saturating to `0` on overflow
267            pub fn saturating_sub(self, offset: u32) -> Self {
268                Self::new(self.to_u32().saturating_sub(offset)).unwrap_or_default()
269            }
270        }
271
272        impl From<::core::num::NonZeroU32> for $number_name {
273            #[inline]
274            fn from(index: ::core::num::NonZeroU32) -> Self {
275                Self(index)
276            }
277        }
278
279        impl From<$index_name> for $number_name {
280            #[inline]
281            fn from(index: $index_name) -> Self {
282                index.number()
283            }
284        }
285
286        impl ::core::ops::Add<u32> for $number_name {
287            type Output = Self;
288
289            #[inline]
290            fn add(self, rhs: u32) -> Self {
291                self.checked_add(rhs)
292                    .expect("line or column number overflowed while adding an offset")
293            }
294        }
295
296        impl ::core::ops::AddAssign<u32> for $number_name {
297            fn add_assign(&mut self, rhs: u32) {
298                let result = *self + rhs;
299                *self = result;
300            }
301        }
302
303        impl ::core::ops::Add<i32> for $number_name {
304            type Output = Self;
305
306            fn add(self, rhs: i32) -> Self {
307                self.to_u32()
308                    .checked_add_signed(rhs)
309                    .and_then(Self::new)
310                    .expect("invalid offset: overflow occurred")
311            }
312        }
313
314        impl ::core::ops::AddAssign<i32> for $number_name {
315            fn add_assign(&mut self, rhs: i32) {
316                let result = *self + rhs;
317                *self = result;
318            }
319        }
320
321        impl ::core::ops::Sub<u32> for $number_name {
322            type Output = Self;
323
324            #[inline]
325            fn sub(self, rhs: u32) -> Self {
326                self.to_u32()
327                    .checked_sub(rhs)
328                    .and_then(Self::new)
329                    .expect("invalid offset: overflow occurred")
330            }
331        }
332
333        impl ::core::ops::SubAssign<u32> for $number_name {
334            fn sub_assign(&mut self, rhs: u32) {
335                let result = *self - rhs;
336                *self = result;
337            }
338        }
339
340        impl ::core::fmt::Display for $number_name {
341            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
342                ::core::fmt::Display::fmt(&self.0, f)
343            }
344        }
345
346        #[cfg(feature = "arbitrary")]
347        impl ::proptest::prelude::Arbitrary for $number_name {
348            type Parameters = ();
349            type Strategy = ::proptest::prelude::BoxedStrategy<Self>;
350
351            fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
352                use proptest::prelude::*;
353                any::<::core::num::NonZeroU32>().prop_map(Self).boxed()
354            }
355        }
356    };
357}
358
359declare_dual_number_and_index_type!(Line, "line");
360declare_dual_number_and_index_type!(Column, "column");
361
362#[cfg(test)]
363mod tests {
364    use super::*;
365
366    #[test]
367    #[should_panic(expected = "exceeds the representable one-based range")]
368    fn maximum_index_cannot_be_converted_to_a_one_based_number() {
369        let _ = LineIndex(u32::MAX).number();
370    }
371
372    #[test]
373    #[should_panic(expected = "overflowed while adding an offset")]
374    fn one_based_number_addition_panics_on_overflow() {
375        let maximum = LineNumber::new(u32::MAX).unwrap();
376        let _ = maximum + 1_u32;
377    }
378}