w_pgn/
lib.rs

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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
mod chess_move;
mod nag;
mod token;
mod tokenizer;
use std::{collections::HashMap, rc::Rc};

use chess_move::{ChessMove, ChessMoveNode};
pub use nag::Nag;
use token::Token;
use tokenizer::Tokenizer;

#[derive(Debug)]
pub struct PGN {
    // Seven Tag Roster
    pub event: Option<String>,
    pub site: Option<String>,
    pub date: Option<String>,
    pub round: Option<String>,
    pub white: Option<String>,
    pub black: Option<String>,
    pub result: Option<String>,
    pub termination: Option<String>,

    pub tags: HashMap<String, String>,

    pub moves: Option<ChessMoveNode>,
}

impl PGN {
    pub fn parse(pgn: &str) -> std::io::Result<Self> {
        let tokens = Tokenizer::new(pgn).tokens;

        PGN::parse_tokens(&tokens)
    }

    pub fn parse_tokens<T>(tokens: T) -> std::io::Result<Self>
    where
        T: AsRef<[Token]>,
    {
        let mut tags = HashMap::new();
        let mut event = None;
        let mut site = None;
        let mut date = None;
        let mut round = None;
        let mut white = None;
        let mut black = None;
        let mut result = None;

        let mut index = 0;

        let mut variation_depth = Vec::new();

        let mut moves = None;

        let tokens = tokens.as_ref();

        let mut termination = None;

        while let Some(token) = tokens.get(index) {
            match token {
                Token::LeftBracket => {
                    if let Some(Token::Symbol(symbol)) = tokens.get(index + 1) {
                        if let Some(Token::String(value)) = tokens.get(index + 2) {
                            match symbol.as_str() {
                                "Event" => {
                                    event = Some(value.clone());
                                }
                                "Site" => {
                                    site = Some(value.clone());
                                }
                                "Date" => {
                                    date = Some(value.clone());
                                }
                                "Round" => {
                                    round = Some(value.clone());
                                }
                                "White" => {
                                    white = Some(value.clone());
                                }
                                "Black" => {
                                    black = Some(value.clone());
                                }
                                "Result" => {
                                    result = Some(value.clone());
                                }
                                _ => {
                                    tags.insert(symbol.clone(), value.clone());
                                }
                            }
                        } else {
                            return Err(std::io::Error::new(
                                std::io::ErrorKind::InvalidData,
                                "Needed a string after tag symbol",
                            ));
                        }

                        if let Some(Token::RightBracket) = tokens.get(index + 3) {
                            index += 4;
                        } else {
                            return Err(std::io::Error::new(
                                std::io::ErrorKind::InvalidData,
                                "Needed a RightBracket after tag value",
                            ));
                        }
                    } else {
                        return Err(std::io::Error::new(
                            std::io::ErrorKind::InvalidData,
                            "Needed a symbol after LeftBracket",
                        ));
                    }
                }
                Token::RightBracket => {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "Unexpected RightBracket",
                    ));
                }

                Token::Symbol(m) => {
                    if !is_valid_san(m) {
                        index += 1;
                    } else {
                        if let Some(ref mut current_move) = moves {
                            let variation = ChessMove::new(m);
                            if variation_depth.len() == 0 {
                                variation.borrow_mut().parent = Some(Rc::downgrade(current_move));
                                current_move.borrow_mut().add_variation(variation.clone());
                            } else if let Some(variation_turn) = variation_depth.last() {
                                if let Some(parent) =
                                    current_move.borrow().get_piece_at_turn(*variation_turn)
                                {
                                    variation.borrow_mut().parent = Some(Rc::downgrade(&parent));
                                    parent.borrow_mut().add_variation(variation.clone());
                                }
                            }
                        } else {
                            moves = Some(ChessMove::new(m));
                        }
                        index += 1;
                    }
                }

                Token::LeftParenthesis => {
                    if let Some(Token::Symbol(symbol)) = tokens.get(index + 1) {
                        if let Some(turn) = symbol.parse::<usize>().ok() {
                            variation_depth.push(turn);
                        } else {
                            return Err(std::io::Error::new(
                                std::io::ErrorKind::InvalidData,
                                "Expected a number after LeftParenthesis",
                            ));
                        }
                    }
                    index += 2;
                }

                Token::RightParenthesis => {
                    if variation_depth.len() > 0 {
                        variation_depth.pop();
                    } else {
                        return Err(std::io::Error::new(
                            std::io::ErrorKind::InvalidData,
                            "Unexpected RightParenthesis",
                        ));
                    }
                    index += 1;
                }

                Token::String(s) => {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        format!("Unexpected string: {}", s),
                    ));
                }

                Token::Termination(s) => {
                    termination = Some(s.clone());
                    break;
                }

                _ => {
                    index += 1;
                }
            }
        }

        Ok(PGN {
            event,
            site,
            date,
            round,
            white,
            black,
            result,
            termination,
            tags,
            moves,
        })
    }

    pub fn parse_multiple(pgns: &str) -> std::io::Result<Vec<Self>> {
        let mut pgn_vec = Vec::new();

        let tokens = Tokenizer::new(pgns).tokens;

        let mut start = 0;

        for (index, token) in tokens.iter().enumerate() {
            match token {
                Token::Termination(_) => {
                    let pgn = PGN::parse_tokens(&tokens[start..=index])?;
                    pgn_vec.push(pgn);
                    start = index + 1;
                }
                _ => {}
            }
        }

        Ok(pgn_vec)
    }

    pub fn moves(&self) -> Vec<String> {
        if let Some(moves) = &self.moves {
            moves.borrow().get_moves()
        } else {
            Vec::new()
        }
    }
}

impl std::fmt::Display for PGN {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(event) = &self.event {
            writeln!(f, "[Event \"{}\"]", event)?;
        } else {
            writeln!(f, "[Event \"?\"]")?;
        }

        if let Some(site) = &self.site {
            writeln!(f, "[Site \"{}\"]", site)?;
        } else {
            writeln!(f, "[Site \"?\"]")?;
        }

        if let Some(date) = &self.date {
            writeln!(f, "[Date \"{}\"]", date)?;
        } else {
            writeln!(f, "[Date \"?\"]")?;
        }

        if let Some(round) = &self.round {
            writeln!(f, "[Round \"{}\"]", round)?;
        } else {
            writeln!(f, "[Round \"?\"]")?;
        }

        if let Some(white) = &self.white {
            writeln!(f, "[White \"{}\"]", white)?;
        } else {
            writeln!(f, "[White \"?\"]")?;
        }

        if let Some(black) = &self.black {
            writeln!(f, "[Black \"{}\"]", black)?;
        } else {
            writeln!(f, "[Black \"?\"]")?;
        }

        if let Some(result) = &self.result {
            writeln!(f, "[Result \"{}\"]", result)?;
        } else {
            writeln!(f, "[Result \"*\"]")?;
        }

        for (key, value) in &self.tags {
            writeln!(f, "[{} \"{}\"]", key, value)?;
        }

        writeln!(f)?;

        if let Some(termination) = &self.termination {
            let moves = self.moves();

            let mut buffer = String::new();
            let mut current_char_count = 0;

            for (index, pair) in moves.chunks(2).enumerate() {
                let mut move_string = format!("{}.{}", index + 1, pair[0]);

                if pair.len() == 2 {
                    move_string.push_str(&format!(" {}", pair[1]));
                }

                let len = move_string.len();

                if current_char_count + len >= 80 {
                    buffer.push('\n');
                    buffer.push_str(&move_string);
                    current_char_count = len;
                } else {
                    if current_char_count > 0 {
                        buffer.push(' ');
                        current_char_count += 1;
                    }
                    buffer.push_str(&move_string);
                    current_char_count += len;
                }
            }

            write!(f, "{}  {}", buffer, termination)?;
        }

        Ok(())
    }
}

fn is_valid_san(san: &str) -> bool {
    let stripped_san: String = san
        .chars()
        .filter(|c| match c {
            '+' | '#' | '=' | '!' | '?' | 'x' => false,
            _ => true,
        })
        .collect();

    if stripped_san == "O-O" || stripped_san == "O-O-O" {
        return true;
    }

    if stripped_san.len() < 2 || stripped_san.len() > 4 {
        return false;
    }

    let mut chars = stripped_san.chars().peekable();

    // Piece check
    if let Some(&first_char) = chars.peek() {
        match first_char {
            'a'..='h' => {}
            'K' | 'Q' | 'R' | 'B' | 'N' => {
                chars.next();
            }
            _ => return false,
        }
    }

    for char in chars {
        match char {
            'a'..='h' | '1'..='8' | 'x' => (),
            _ => return false,
        }
    }

    true
}

#[cfg(test)]
mod tests {
    use std::io::{Read, Write};

    use super::*;

    #[test]
    fn test_parse() {
        let pgn_input = r#"[Event "F/S Return Match"]
        [Site "Belgrade, Serbia JUG"]
        [Date "1992.11.04"]
        [Round "29"]
        [White "Fischer, Robert J."]
        [Black "Spassky, Boris V."]
        [Result "1/2-1/2"]

        1. e4 e5 2. Nf3 Nc6 3. Bb5 {This opening is called the Ruy Lopez.} 3... a6
        4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Nb8 10. d4 Nbd7
        11. c4 c6 12. cxb5 axb5 13. Nc3 Bb7 14. Bg5 b4 15. Nb1 h6 16. Bh4 c5 17. dxe5
        Nxe4 18. Bxe7 Qxe7 19. exd6 Qf6 20. Nbd2 Nxd6 21. Nc4 Nxc4 22. Bxc4 Nb6
        23. Ne5 Rae8 24. Bxf7+ Rxf7 25. Nxf7 Rxe1+ 26. Qxe1 Kxf7 27. Qe3 Qg5 28. Qxg5
        hxg5 29. b3 Ke6 30. a3 Kd6 31. axb4 cxb4 32. Ra5 Nd5 33. f3 Bc8 34. Kf2 Bf5
        35. Ra7 g6 36. Ra6+ Kc5 37. Ke1 Nf4 38. g3 Nxh3 39. Kd2 Kb5 40. Rd6 Kc5 41. Ra6
        Nf2 42. g4 Bd3 43. Re6 1/2-1/2
        "#;

        let pgn = PGN::parse(pgn_input).unwrap();

        assert_eq!(pgn.event, Some("F/S Return Match".to_string()));
        assert_eq!(pgn.site, Some("Belgrade, Serbia JUG".to_string()));
        assert_eq!(pgn.date, Some("1992.11.04".to_string()));
        assert_eq!(pgn.round, Some("29".to_string()));
        assert_eq!(pgn.white, Some("Fischer, Robert J.".to_string()));
        assert_eq!(pgn.black, Some("Spassky, Boris V.".to_string()));
        assert_eq!(pgn.result, Some("1/2-1/2".to_string()));

        if let Some(moves) = pgn.moves {
            moves.borrow().print_tree(0);
        }
    }

    #[test]
    fn my_game() {
        let mut buffer = String::new();

        let mut file = std::fs::File::open("game.pgn").unwrap();

        file.read_to_string(&mut buffer).unwrap();

        let pgn = PGN::parse(&buffer).unwrap();

        if let Some(moves) = pgn.moves {
            moves.borrow().print_tree(0);
        }
    }

    #[test]
    fn multiple_games() {
        let mut buffer = String::new();

        let mut file = std::fs::File::open("Abdusattorov.pgn").unwrap();

        file.read_to_string(&mut buffer).unwrap();

        let pgns = PGN::parse_multiple(&buffer).unwrap();

        let mut buffer = String::new();

        for pgn in pgns {
            buffer += &format!("{}\n\n", pgn);
        }

        let mut file = std::fs::File::create("output.pgn").unwrap();

        file.write_all(buffer.as_bytes()).unwrap();
    }
}