jja 0.9.1

swiss army knife for chess file formats
Documentation
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//
// jja: swiss army knife for chess file formats
// src/pgn.rs: Portable Game Notation utilities
//
// Copyright (c) 2023, 2024 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0-or-later

use std::{
    fmt::{self, Display, Formatter},
    fs::File,
    io::{stdout, Read, StdoutLock, Write},
    str::FromStr,
};

use anyhow::{bail, Context};
use indicatif::ProgressBar;
use pgcopy::Encoder;
use pgn_reader::{BufferedReader, RawHeader, SanPlus, Skip, Visitor};
use shakmaty::{
    fen::{Epd, Fen},
    CastlingMode, Chess, EnPassantMode, Position, PositionError,
};

use crate::{
    chess::serialize_chess,
    hash::{zobrist16_hash, zobrist32_hash, zobrist8_hash, zobrist_hash},
    stockfish::stockfish_hash,
    system::get_progress_bar,
    tr,
};

/// Output formats for `pgn_dump` function.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum OutputFormat {
    /// Represents the PostgreSQL binary output format.
    Binary,
    /// Represents the CSV output format.
    Csv,
    /// Represents the JSON output format.
    Json,
    /// Represents the EPD output format.
    Epd,
}

impl Display for OutputFormat {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            OutputFormat::Binary => write!(f, "BIN"),
            OutputFormat::Csv => write!(f, "CSV"),
            OutputFormat::Json => write!(f, "JSON"),
            OutputFormat::Epd => write!(f, "EPD"),
        }
    }
}

/// Dump elements for `pgn_dump` function.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum DumpElement {
    /// Represents a Zobrist8 hash of the position.
    Zobrist8,
    /// Represents a Zobrist16 hash of the position.
    Zobrist16,
    /// Represents a Zobrist32 hash of the position.
    Zobrist32,
    /// Represents a Zobrist64 hash of the position.
    Zobrist64,
    /// Represents a Stockfish compatible Zobrist64 hash of the position.
    Zobrist64SF,
    /// Represents a serialized array of the position.
    Position,
}

impl Display for DumpElement {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            DumpElement::Zobrist8 => write!(f, "zobrist8"),
            DumpElement::Zobrist16 => write!(f, "zobrist16"),
            DumpElement::Zobrist32 => write!(f, "zobrist8"),
            DumpElement::Zobrist64 => write!(f, "zobrist64"),
            DumpElement::Zobrist64SF => write!(f, "zobrist64sf"),
            DumpElement::Position => write!(f, "position"),
        }
    }
}

impl FromStr for DumpElement {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "z8" | "zobrist8" => Ok(DumpElement::Zobrist8),
            "z16" | "zobrist16" => Ok(DumpElement::Zobrist16),
            "z32" | "zobrist32" => Ok(DumpElement::Zobrist32),
            "id" | "z64" | "zobrist64" => Ok(DumpElement::Zobrist64),
            "sf" | "z64sf" | "zobrist64sf" => Ok(DumpElement::Zobrist64SF),
            "p" | "pos" | "position" => Ok(DumpElement::Position),
            _ => Err(()),
        }
    }
}

/// `PositionTracker` is a struct that represents a chess position and tracks its validity.
///
/// # Fields
/// * `position`: A `Chess` struct representing the current chess position.
/// * `init`: A boolean that indicates whether the initial position of the game was processed.
/// * `valid`: A boolean that indicates whether the position is valid or not.
/// * `output`: Writer for all text output. If `PositionTracker::new` was called with
/// `None` as output argument, then this writer is going to direct to the standard output.
/// * `format`: A `Option<OutputFormat>` representing the optional output format.
pub struct PositionTracker<'a> {
    position: Chess,
    init: bool,
    valid: bool,
    output: Box<dyn Write + 'a>,
    format: Option<OutputFormat>,
    elements: Option<&'a Vec<DumpElement>>,
    progress_bar: Option<&'a ProgressBar>,
    postgres_enc: Option<Encoder<StdoutLock<'a>>>,
}

impl<'a> PositionTracker<'a> {
    /// Constructs a new `PositionTracker` with the default chess position and sets the `valid`
    /// field to `true`.
    ///
    /// # Arguments
    ///
    /// - `output: Option<Box<dyn Write + 'a>>`: Optional writer for text output, for Postgresql
    /// binary output use the encoder argument. If `None`, the text output will be sent to the
    /// standard output.
    /// - `format: Option<OutputFormat>`: Optional output format.
    /// - `elements: Option<DumpElement>`: Optional list of elements.
    /// - `encoder: Option<Encoder<StdoutLock<'a>>>`: Optional Postgresql encoder.
    /// - `progress_bar: Option<&ProgressBar>`: Optional progress bar.
    ///
    /// # Returns
    /// A new instance of `PositionTracker`.
    pub fn new(
        output: Option<Box<dyn Write + 'a>>,
        format: Option<OutputFormat>,
        elements: Option<&'a Vec<DumpElement>>,
        encoder: Option<Encoder<StdoutLock<'a>>>,
        progress_bar: Option<&'a ProgressBar>,
    ) -> Self {
        let output = match output {
            Some(file) => file,
            None => Box::new(stdout()),
        };

        PositionTracker {
            output,
            format,
            elements,
            progress_bar,
            postgres_enc: encoder,
            position: Chess::default(),
            init: false,
            valid: true,
        }
    }

    fn write_header(&mut self) -> anyhow::Result<()> {
        if let Some(encoder) = self.postgres_enc.as_mut() {
            encoder
                .write_header()
                .context(tr!("Failed to write PostgreSQL binary header"))?;
        }

        Ok(())
    }

    fn write_trailer(&mut self) -> anyhow::Result<()> {
        if let Some(encoder) = self.postgres_enc.as_mut() {
            encoder
                .write_trailer()
                .context(tr!("Failed to write PostgreSQL binary trailer"))?;
        }

        Ok(())
    }

    fn dump_position(&mut self) {
        if let Some(format) = self.format {
            if format == OutputFormat::Epd {
                // TODO: Add context from PGN headers into c0 & c1 fields like pgn-extract.
                // TODO: Use --elements to let the user pick which EPD fields to print.
                writeln!(
                    self.output,
                    "{} id {:#x};",
                    Epd::from_position(self.position.clone(), EnPassantMode::PseudoLegal),
                    zobrist_hash(&self.position)
                )
                .expect("epd write");

                if let Some(progress_bar) = &self.progress_bar {
                    progress_bar.inc(1);
                }
                return;
            }

            let mut elements = Vec::new();
            if let Some(dump_elements) = self.elements {
                for dump_element in dump_elements {
                    match dump_element {
                        DumpElement::Zobrist8 => {
                            elements.push(u64::from(zobrist8_hash(&self.position)));
                        }
                        DumpElement::Zobrist16 => {
                            elements.push(u64::from(zobrist16_hash(&self.position)));
                        }
                        DumpElement::Zobrist32 => {
                            elements.push(u64::from(zobrist32_hash(&self.position)));
                        }
                        DumpElement::Zobrist64 => {
                            elements.push(zobrist_hash(&self.position));
                        }
                        DumpElement::Zobrist64SF => {
                            elements.push(stockfish_hash(&self.position));
                        }
                        DumpElement::Position => {
                            elements.extend(serialize_chess(&self.position));
                        }
                    }
                }
            } else {
                elements.push(zobrist_hash(&self.position));
                elements.extend(serialize_chess(&self.position));
            }

            match format {
                OutputFormat::Binary => {
                    // SAFETY: output format guarantees postgres_enc is Some.
                    let enc = unsafe { self.postgres_enc.as_mut().unwrap_unchecked() };
                    enc.write_tuple(elements.len() as i16)
                        .expect("pgcopy write tuple");
                    for element in elements {
                        enc.write_bigint(element as i64)
                            .expect("pgcopy write element");
                    }
                }
                // TODO: Honour self.output rather than printing directly to standard output.
                // Currently there is no CLI argument to specify such output so until then we do
                // not implement it here either to keep things simple.
                OutputFormat::Csv => {
                    for (idx, element) in elements.into_iter().enumerate() {
                        print!("{}{}", if idx == 0 { "" } else { "," }, element as i64);
                    }
                    println!();
                }
                OutputFormat::Json => {
                    print!("[");
                    for (idx, element) in elements.into_iter().enumerate() {
                        print!("{}{}", if idx == 0 { "" } else { "," }, element);
                    }
                    println!("]");
                }
                // OutputFormat::Epd has already been handled above.
                _ => unreachable!(),
            }

            if let Some(progress_bar) = &self.progress_bar {
                progress_bar.inc(1);
            }
        }
    }
}

/// Implementing the `Visitor` trait for the `PositionTracker` struct.
/// This allows the struct to handle chess games represented in SAN notation,
/// including playing moves, handling variations, and ending the game.
///
/// The `Result` type is set to `Chess`.
impl Visitor for PositionTracker<'_> {
    type Result = Chess;

    fn header(&mut self, key: &[u8], value: RawHeader<'_>) {
        if key != b"FEN" {
            return;
        }

        // Support games from a non-standard starting position.
        let fen = match Fen::from_ascii(value.as_bytes()) {
            Ok(fen) => fen,
            Err(err) => {
                eprintln!(
                    "{}",
                    tr!(
                        "Skipping invalid FEN header: {} ({}).",
                        err,
                        format!("{:?}", value)
                    )
                );
                self.valid = false;
                return;
            }
        };

        self.position = match fen
            .into_position(CastlingMode::Chess960)
            .or_else(PositionError::ignore_invalid_ep_square)
            .or_else(PositionError::ignore_invalid_castling_rights)
        {
            Ok(pos) => pos,
            Err(err) => {
                eprintln!(
                    "{}",
                    tr!(
                        "Skipping illegal FEN header: {} ({}).",
                        err,
                        format!("{:?}", value)
                    )
                );
                self.valid = false;
                return;
            }
        };
        // Given multiple FEN headers (which is super-rare and formally
        // broken PGN), we process all of them for dump, and use the
        // last one for position tracker.
        self.dump_position();
        self.init = true;
    }

    fn end_headers(&mut self) -> Skip {
        if !self.init {
            self.dump_position();
            self.init = true;
        }
        Skip(!self.valid)
    }

    /// Processes a move in SAN notation and updates the position.
    ///
    /// If the position is invalid, this function does nothing.
    ///
    /// # Parameters
    /// * `san_plus`: A `SanPlus` containing the move in SAN notation.
    fn san(&mut self, san_plus: SanPlus) {
        if !self.valid {
            return;
        }

        let san = san_plus.san;
        let mov = match san.to_move(&self.position) {
            Ok(mov) => mov,
            Err(err) => {
                let epd = format!(
                    "{}",
                    Epd::from_position(self.position.clone(), EnPassantMode::PseudoLegal)
                );
                eprintln!(
                    "{}",
                    tr!("illegal SAN move `{}' in position `{}': {}", san, epd, err)
                );
                self.valid = false;
                return;
            }
        };

        self.position.play_unchecked(&mov);
        self.dump_position();
    }

    /// Handles the beginning of a variation.
    ///
    /// The implementation always returns `Skip(true)`, which causes the parser
    /// to stay in the mainline and ignore the variation.
    ///
    /// # Returns
    /// A `Skip` instance indicating whether to skip the variation or not.
    fn begin_variation(&mut self) -> Skip {
        Skip(true) // stay in the mainline
    }

    /// Handles the end of the game and resets the position.
    ///
    /// This function clones the current position and then resets the internal
    /// position to the default chess position.
    ///
    /// # Returns
    /// The `Chess` instance representing the final position of
    fn end_game(&mut self) -> Self::Result {
        self.valid = true;
        std::mem::take(&mut self.position)
    }
}

/// Converts a PGN string into an EPD string representing the final position.
///
/// This function takes a PGN string as input, processes the moves, and then
/// returns a string containing the final position in EPD format.
///
/// # Parameters
/// * `pgn`: A `&str` containing the PGN of the chess game.
///
/// # Returns
/// A `String` containing the final position of the game in EPD format.
pub fn pgn2epd(pgn: &str) -> String {
    let mut reader = BufferedReader::new_cursor(pgn);

    let mut tracker: PositionTracker<'_> = PositionTracker::new(None, None, None, None, None);
    let position = reader
        .read_game(&mut tracker)
        .expect("pgn")
        .expect("invalid pgn argument");

    format!(
        "{}",
        Epd::from_position(position, EnPassantMode::PseudoLegal)
    )
}

/// Converts a PGN file into a JSON stream of arrays which is a 6-sized array, the first element is
/// the Zobrist hash, the second to sixth elements are the serialized position as returned by
/// `jja::chess::serialize_chess` function or into a stream of CSV arrays which is again a 6-sized
/// array with the exact same structure as the JSON array except in CSV format the numbers are
/// cast into signed 64-bit numbers, whereas in JSON output they're unsigned 64-bit numbers.
/// Compressed PGN files are supported.
pub fn pgn_dump(
    file_name: &str,
    format: OutputFormat,
    elements: &Vec<DumpElement>,
) -> anyhow::Result<()> {
    eprintln!(
        "{}",
        tr!(
            "Dumping all positions in PGN file `{}' in format {} to standard output...",
            file_name,
            format
        )
    );

    let file = match File::open(file_name) {
        Ok(file) => file,
        Err(err) => {
            bail!(
                "{}",
                tr!("Failed to open PGN file `{}': {}", file_name, err)
            );
        }
    };

    let file_ext = std::path::Path::new(file_name).extension();
    let uncompressed: Box<dyn Read + Send> =
        if file_ext.map_or(false, |ext| ext.eq_ignore_ascii_case("zst")) {
            Box::new(match zstd::Decoder::new(file) {
                Ok(decoder) => decoder,
                Err(err) => {
                    bail!(
                        "{}",
                        tr!("Failed to open PGN file `{}': {}", file_name, err)
                    );
                }
            })
        } else if file_ext.map_or(false, |ext| ext.eq_ignore_ascii_case("bz2")) {
            Box::new(bzip2::read::MultiBzDecoder::new(file))
        } else if file_ext.map_or(false, |ext| ext.eq_ignore_ascii_case("xz")) {
            Box::new(xz2::read::XzDecoder::new(file))
        } else if file_ext.map_or(false, |ext| ext.eq_ignore_ascii_case("gz")) {
            Box::new(flate2::read::GzDecoder::new(file))
        } else if file_ext.map_or(false, |ext| ext.eq_ignore_ascii_case("lz4")) {
            Box::new(match lz4::Decoder::new(file) {
                Ok(decoder) => decoder,
                Err(err) => {
                    bail!(
                        "{}",
                        tr!("Failed to open PGN file `{}': {}", file_name, err)
                    );
                }
            })
        } else {
            Box::new(file)
        };

    let progress_bar = get_progress_bar(0);
    progress_bar.set_message(tr!("Dumping:"));

    let encoder: Option<Encoder<StdoutLock>> = match format {
        OutputFormat::Binary => Some(Encoder::new(stdout().lock())),
        _ => None,
    };

    let mut tracker = PositionTracker::new(
        None,
        Some(format),
        Some(elements),
        encoder,
        Some(&progress_bar),
    );
    tracker.write_header()?;
    BufferedReader::new(uncompressed).read_all(&mut tracker)?;
    tracker.write_trailer()?;

    let count = progress_bar.position();
    progress_bar.finish_and_clear();

    eprintln!(
        "{}",
        tr!(
            "Successfully dumped {} positions from PGN file `{}' in format {} to standard output.",
            count,
            file_name,
            format
        )
    );
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_pgn2epd() {
        let pgn = "1. e4 e5 2. Nf3 Nc6 3. Bb5";
        let epd = pgn2epd(pgn);
        assert_eq!(
            epd,
            "r1bqkbnr/pppp1ppp/2n5/1B2p3/4P3/5N2/PPPP1PPP/RNBQK2R b KQkq -"
        );
    }
}