1use crate::traits::{Error, Position};
2
3#[cfg(not(feature = "std"))]
4extern crate alloc;
5
6#[cfg(not(feature = "std"))]
7use alloc::fmt::Formatter;
8#[cfg(not(feature = "std"))]
9use alloc::vec::Vec;
10
11#[cfg_attr(feature = "std", derive(Debug))]
12#[derive(Copy, Clone, Default, PartialEq, Eq)]
13pub struct SimplePosition {
14 pub index: u32,
15 pub line: u32,
16 pub column: u32,
17}
18
19impl SimplePosition {
20 pub fn next(&self, c: char) -> Self {
21 let new_line = c == '\n';
22 Self {
23 index: self.index + 1,
24 line: if new_line { self.line + 1 } else { self.line },
25 column: if new_line { 0 } else { self.column + 1 },
26 }
27 }
28}
29
30impl Position for SimplePosition {
31 fn index(&self) -> u32 {
32 self.index
33 }
34
35 fn line(&self) -> u32 {
36 self.line
37 }
38
39 fn column(&self) -> u32 {
40 self.column
41 }
42}
43
44impl core::ops::Sub<Self> for SimplePosition {
45 type Output = i32;
46
47 fn sub(self, rhs: SimplePosition) -> Self::Output {
48 if self.index > rhs.index {
49 (self.index - rhs.index) as i32
50 } else {
51 -((rhs.index - self.index) as i32)
52 }
53 }
54}
55
56#[cfg_attr(feature = "std", derive(Debug, PartialEq, Eq))]
57pub struct SimpleError {
58 pub reasons: Vec<(SimplePosition, &'static str)>,
59}
60
61#[cfg(not(feature = "std"))]
62impl core::fmt::Debug for SimpleError {
63 fn fmt(&self, _f: &mut Formatter<'_>) -> core::fmt::Result {
64 Ok(())
65 }
66}
67
68impl Error for SimpleError {
69 type Position = SimplePosition;
70
71 fn reasons(&self) -> &[(Self::Position, &'static str)] {
72 &self.reasons[..]
73 }
74
75 fn add_reason(self, position: Self::Position, reason: &'static str) -> Self {
76 let mut reasons = self.reasons;
77 reasons.push((position, reason));
78 Self { reasons }
79 }
80}