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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
use fen4::{Position, PositionParseError};
use std::str::FromStr;

use crate::types::*;

use thiserror::Error;

#[derive(Error, PartialEq, Clone, Debug)]
pub enum MoveError {
    #[error("Basic move is malformed.")]
    Other,
    #[error("A move starts with O-O, but is not a correct type of move.")]
    Castle,
    #[error("Unable to parse basic move because {0}")]
    PositionInvalid(#[from] PositionParseError),
}
impl FromStr for BasicMove {
    type Err = MoveError;
    fn from_str(string: &str) -> Result<Self, Self::Err> {
        let mut iter = string.chars();
        let start = iter.next().ok_or(MoveError::Other)?;
        let (piece, pieceless) = if start.is_ascii_lowercase() {
            ('P', string)
        } else {
            (start, iter.as_str())
        };
        let mateless = pieceless.trim_end_matches('#');
        let checkless = mateless.trim_end_matches('+');

        let mates = pieceless.len() - mateless.len();
        let checks = mateless.len() - checkless.len();

        let (two_pos, promotion) = if let Some(equals) = checkless.find('=') {
            let (left_over, promote) = checkless.split_at(equals);
            let mut iter = promote.chars();
            if iter.next() != Some('=') {
                return Err(MoveError::Other);
            }
            let p = iter.next().ok_or(MoveError::Other)?;
            if iter.next().is_some() {
                return Err(MoveError::Other);
            }
            (left_over, Some(p))
        } else {
            (checkless, None)
        };

        let loc = if let Some(dash) = two_pos.find('-') {
            dash
        } else if let Some(x) = two_pos.find('x') {
            x
        } else {
            return Err(MoveError::Other);
        };
        let (left, tmp) = two_pos.split_at(loc);
        let (mid, mut right) = tmp.split_at(1); // x and - are both ascii and therefore 1 byte
        let from = left.parse::<Position>()?;
        let captured = if mid == "x" {
            let mut iter = right.chars();
            let start = iter.next().ok_or(MoveError::Other)?;
            Some(if start.is_ascii_lowercase() {
                'P'
            } else {
                right = iter.as_str();
                start
            })
        } else {
            None
        };
        let to = right.parse::<Position>()?;
        Ok(BasicMove {
            piece,
            from,
            captured,
            to,
            promotion,
            checks,
            mates,
        })
    }
}

impl FromStr for Move {
    type Err = MoveError;
    fn from_str(string: &str) -> Result<Self, Self::Err> {
        use Move::*;
        Ok(match string {
            "C" => Claim,
            "#" => Checkmate,
            "S" => Stalemate,
            "T" => Timeout,
            "R" => Resign,
            s if s.starts_with("O-O") => {
                let mateless = s.trim_end_matches('#');
                let mates = s.len() - mateless.len();
                match mateless {
                    "O-O-O" => QueenCastle(mates),
                    "O-O" => KingCastle(mates),
                    _ => return Err(MoveError::Castle),
                }
            }
            _ => Normal(string.parse::<BasicMove>()?),
        })
    }
}

struct MovePair {
    main: Move,
    modifier: Option<Move>,
}

impl FromStr for MovePair {
    type Err = MoveError;
    fn from_str(string: &str) -> Result<Self, Self::Err> {
        let break_index = if string.len() == 2 {
            1 // No move is 2 bytes long
        } else if string.len() > 2 {
            if (string.ends_with('R') && !string.ends_with("=R"))
                || (string.ends_with('S') && !string.ends_with("=S"))
                || (string.ends_with('T') && !string.ends_with("=T"))
            {
                string.len() - 1
            } else {
                0
            }
        } else {
            0
        };
        Ok(if break_index == 0 {
            Self {
                main: string.parse()?,
                modifier: None,
            }
        } else {
            Self {
                main: string.get(..break_index).ok_or(MoveError::Other)?.parse()?,
                modifier: Some(string.get(break_index..).ok_or(MoveError::Other)?.parse()?),
            }
        })
    }
}

#[derive(PartialEq, Clone, Debug)]
enum IntermediateError {
    Other(usize),
    MoveErr(MoveError, String, usize),
    Description(usize),
}

fn parse_quarter(string: &str) -> Result<(QuarterTurn, &str), IntermediateError> {
    /// Generally the move is bounded by whitespace, but supporting pgns that don't
    /// have all the neccessary whitespace is good. Notably, whitespace before a new
    ///  line number is critical.
    fn next_move(c: char) -> bool {
        c.is_whitespace()
            || match c {
                '.' | '{' | '(' | ')' => true,
                _ => false,
            }
    }
    use IntermediateError::*;
    let trimmed = string.trim_start();
    if trimmed == "" {
        return Err(Other(trimmed.len()));
    }
    let split = trimmed.find(next_move).unwrap_or(string.len() - 1);
    let (main_str, mut rest) = trimmed.split_at(split);
    let move_pair = main_str
        .trim()
        .parse::<MovePair>()
        .map_err(|m| MoveErr(m, main_str.to_owned(), rest.len()))?;
    let mut description = None;
    let mut alternatives = Vec::new();
    rest = rest.trim_start();

    if let Some(c) = rest.chars().next() {
        if c == '{' {
            let desc_end = rest.find('}').ok_or(Description(rest.len()))?;
            let (mut desc_str, rest_tmp) = rest.split_at(desc_end + 1);
            desc_str = desc_str.strip_prefix("{ ").ok_or(Description(rest.len()))?;
            desc_str = desc_str.strip_suffix(" }").ok_or(Description(rest.len()))?;
            description = Some(desc_str.to_owned());
            rest = rest_tmp;
        }
    } else {
        return Ok((
            QuarterTurn {
                main: move_pair.main,
                modifier: move_pair.modifier,
                description,
                alternatives,
            },
            rest,
        ));
    };

    while let Some(rest_tmp) = rest.strip_prefix('(') {
        rest = rest_tmp;
        let mut turns = Vec::new();
        while rest.chars().next() != Some(')') {
            let (turn, rest_tmp) = parse_turn(rest)?;
            rest = rest_tmp;
            turns.push(turn);
        }
        rest = rest.strip_prefix(')').unwrap().trim_start();
        alternatives.push(turns);
    }
    Ok((
        QuarterTurn {
            main: move_pair.main,
            modifier: move_pair.modifier,
            description,
            alternatives,
        },
        rest,
    ))
}

fn parse_turn(string: &str) -> Result<(Turn, &str), IntermediateError> {
    use IntermediateError::*;
    let trimmed = string.trim_start();
    let dot_loc = trimmed.find('.').ok_or(Other(trimmed.len()))?;
    let (number_str, dots) = trimmed.split_at(dot_loc);
    let number = if number_str == "" {
        0
    } else {
        number_str.parse().map_err(|_| Other(trimmed.len()))?
    };
    let dot = dots.strip_prefix('.').unwrap();
    let (mut rest, double_dot) = if let Some(dotted) = dot.strip_prefix('.') {
        (dotted, true)
    } else {
        (dot, false)
    };
    let mut turns = Vec::new();
    let for_error = rest.len();
    let (qturn, rest_tmp) = parse_quarter(rest)?;
    rest = rest_tmp.trim_start();
    turns.push(qturn);
    while let Some(rest_tmp) = rest.strip_prefix("..") {
        if turns.len() >= 4 {
            return Err(Other(for_error));
        }
        let (qturn, rest_tmp) = parse_quarter(rest_tmp)?;
        rest = rest_tmp.trim_start();
        turns.push(qturn);
    }
    Ok((
        Turn {
            number,
            double_dot,
            turns,
        },
        rest,
    ))
}

#[derive(Error, PartialEq, Clone, Debug)]
pub enum PGN4Error {
    #[error("Some error occured at {0}")]
    Other(ErrorLocation),
    #[error("Tag starting at {0} is malformed")]
    BadTagged(ErrorLocation),
    #[error("Move \"{1}\" at {2} failed to parse. {0}")]
    BadMove(MoveError, String, ErrorLocation),
    #[error("Description starting at {0} is malformed")]
    BadDescription(ErrorLocation),
}

#[derive(PartialEq, Clone, Debug)]
pub struct ErrorLocation {
    pub line: usize,
    pub column: usize,
    pub raw_offset: usize,
}

impl std::fmt::Display for ErrorLocation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "line {} column {}", self.line, self.column)
    }
}

impl FromStr for PGN4 {
    type Err = PGN4Error;
    fn from_str(string: &str) -> Result<Self, Self::Err> {
        let mut bracketed = Vec::new();
        let mut rest = string;
        while let Some(rest_tmp) = rest.strip_prefix('[') {
            let label_end = rest_tmp.find(|c: char| c.is_whitespace()).unwrap_or(0);
            let (label, middle) = rest_tmp.split_at(label_end);
            rest = middle
                .trim_start()
                .strip_prefix('"')
                .ok_or_else(|| make_tagged(rest_tmp, string))?;

            let value_end = rest
                .find('"')
                .ok_or_else(|| make_tagged(rest_tmp, string))?;
            let (value, end) = rest.split_at(value_end);
            rest = end
                .strip_prefix("\"]")
                .ok_or_else(|| make_tagged(rest_tmp, string))?
                .trim_start();

            bracketed.push((label.to_owned(), value.to_owned()));
        }
        let mut turns = Vec::new();
        while rest != "" {
            let (turn, rest_tmp) = parse_turn(rest).map_err(|ie| add_details(ie, string))?;
            rest = rest_tmp;
            turns.push(turn);
        }
        Ok(PGN4 { bracketed, turns })
    }
}

fn map_location(bytes_left: usize, base: &str) -> ErrorLocation {
    let front = base.split_at(base.len() - bytes_left).0;
    let from_last_newline = front.lines().last().unwrap();
    let line = front.lines().count();
    ErrorLocation {
        line,
        column: from_last_newline.chars().count(),
        raw_offset: front.len(),
    }
}

fn make_tagged(rest: &str, string: &str) -> PGN4Error {
    PGN4Error::BadTagged(map_location(rest.len(), string))
}

fn add_details(ie: IntermediateError, string: &str) -> PGN4Error {
    use IntermediateError::*;
    match ie {
        Other(r) => PGN4Error::Other(map_location(r, string)),
        MoveErr(m, e, r) => PGN4Error::BadMove(m, e, map_location(r, string)),
        Description(r) => PGN4Error::BadDescription(map_location(r, string)),
    }
}