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
use std::ops::RangeInclusive;

#[derive(Clone, Copy, PartialEq)]
pub struct Input<'a> {
    string: &'a str,
    index: usize,
    line: usize,
}

impl<'a> Input<'a> {
    pub fn new(string: &'a str) -> Self {
        Self {
            string,
            index: 0,
            line: 1,
        }
    }

    pub fn span_to(&self, other: Self) -> Span<'a> {
        let string = self.string;
        let start = self.index;
        let end = other.index;
        let line = self.line;

        Span { string, start, end, line }
    }

    pub fn advance(mut self, offset: usize) -> Self {
        self.index += offset;
        self
    }

    fn curr(&self) -> &'a str {
        self.string.get(self.index..).unwrap_or("")
    }

    pub fn exact<E: Exact>(&self, exact: E) -> Option<(Self, ())> {
        let curr = self.curr();
        let rest = exact.exact(curr)?;
        let delta = curr.len() - rest.len();
        let interim = &curr[..delta];
        let newlines = interim.chars().fold(0, |acc, c| if c == '\n' {
            acc + 1
        } else {
            acc
        });
        let input = Self {
            string: self.string,
            index: self.index + delta,
            line: self.line + newlines,
        };
        Some((input, ()))
    }
}

impl<'a> std::fmt::Debug for Input<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let slice = self.curr();
        let slice = &slice[..slice.len().min(15)];
        write!(f, "Input({:?} ({}) {:?})", self.index, self.line, slice)
    }
}

#[test]
fn test_debug_input() {
    let string = "word\nword\nword";
    let index = 5;
    let line = 2;
    let input = Input { string, index, line };
    assert_eq!(format!("{:?}", &input), "Input(5 (2) \"word\\nword\")".to_string());
}

#[derive(Clone, Copy, PartialEq)]
pub struct Span<'a> {
    string: &'a str,
    start: usize,
    end: usize,
    line: usize,
}

impl<'a> Span<'a> {
    pub fn slice(&self) -> &'a str {
        self.string.get(self.start..self.end).expect("Bad span.")
    }

    pub fn column(&self) -> usize {
        let string = &self.string[..self.start];
        let index = string.rfind('\n').map(|i| i + 1).unwrap_or(0);
        self.start - index + 1
    }
    
    pub fn error(&self, message: &str) -> String {
        let start = self.string
            .get(..self.start)
            .unwrap()
            .rfind('\n')
            .map(|i| i + 1)
            .unwrap_or(0);
        let end = self.string
            .get(self.end..)
            .unwrap()
            .find('\n')
            .unwrap_or(self.string.len());
        format!(
            "[Error {line}:{column}] {message}\n{content}\n{leading}{carets}",
            line    = self.line,
            column  = self.column(),
            message = message,
            content = &self.string[start..end],
            leading = " ".repeat(self.column() - 1),
            carets  = "^".repeat(self.end - self.start),
        )
    }
}

impl<'a> std::fmt::Debug for Span<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let slice = self.slice();
        write!(f, "Span({:?} ({}) {:?})", self.start..self.end, self.line, slice)
    }
}

#[test]
fn test_debug_span() {
    let string = "word\nword\nword";
    let start = 5;
    let end = 9;
    let line = 2;
    let span = Span { string, start, end, line };
    assert_eq!(format!("{:?}", span), "Span(5..9 (2) \"word\")".to_string());
}

pub trait Exact {
    fn exact<'a>(&self, input: &'a str) -> Option<&'a str>;
}

/// Parse a prefix matching the char exactly
impl Exact for char {
    fn exact<'a>(&self, input: &'a str) -> Option<&'a str> {
        input.strip_prefix(*self)
    }
}

/// Parse a prefix matching the &str exactly
impl Exact for &str {
    fn exact<'a>(&self, input: &'a str) -> Option<&'a str> {
        input.strip_prefix(self)
    }
}

/// Parse *any* of the characters in the inclusive range
impl Exact for RangeInclusive<char> {
    fn exact<'a>(&self, input: &'a str) -> Option<&'a str> {
        let c = input.chars().next()?;
        if self.contains(&c) {
            Some(&input[c.len_utf8()..])
        } else {
            None
        }
    }
}

/// Parse a single character matching the predicate
impl<F> Exact for F
where
    F: Fn(char) -> bool
{
    fn exact<'a>(&self, input: &'a str) -> Option<&'a str> {
        input.strip_prefix(self)
    }
}

#[test]
fn test_exact() {
    let input = Input::new("1234");
    let mut out = input;
    out.index += 1;
    assert_eq!(input.exact('0'..='9'), Some((out, ())));

    let input = Input::new("Hello");
    let mut out = input;
    out.index += 1;
    assert_eq!(input.exact('H'), Some((out, ())));

    let input = Input::new("Hello");
    let mut out = input;
    out.index += 5;
    assert_eq!(input.exact("Hello"), Some((out, ())));
}

#[test]
fn test_span_to() {
    let input = Input::new("1234");
    let mut rest = input;
    rest.index += 2;
    let span = input.span_to(rest);
    assert_eq!(span, Span {
        string: "1234",
        start: 0,
        end: 2,
        line: 1,
    });
}

#[test]
fn test_advance() {
    let input = Input::new("1234");
    assert_eq!(input.advance(2).index, 2);
}