shakmaty 0.30.0

Chess and chess variant rules and operations
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
//! Parse and write moves in Universal Chess Interface representation.
//!
//! # Examples
//!
//! Parsing UCI moves:
//!
//! ```
//! use shakmaty::{Square, uci::UciMove};
//!
//! let uci: UciMove = "g1f3".parse()?;
//!
//! assert_eq!(uci, UciMove::Normal {
//!     from: Square::G1,
//!     to: Square::F3,
//!     promotion: None,
//! });
//!
//! # Ok::<_, shakmaty::uci::ParseUciMoveError>(())
//! ```
//!
//! Converting to a legal move in the context of a position:
//!
//! ```
//! # use shakmaty::{Square, uci::{IllegalUciMoveError, ParseUciMoveError, UciMove}};
//! use shakmaty::{Color::White, Chess, Setup, Position};
//!
//! # let uci: UciMove = "g1f3".parse()?;
//! let mut pos = Chess::default();
//! let m = uci.to_move(&pos)?;
//!
//! pos.play_unchecked(m);
//! assert_eq!(pos.board().piece_at(Square::F3), Some(White.knight()));
//!
//! # #[derive(Debug)] struct CommonError;
//! # impl From<IllegalUciMoveError> for CommonError { fn from(_: IllegalUciMoveError) -> Self { Self } }
//! # impl From<ParseUciMoveError> for CommonError { fn from(_: ParseUciMoveError) -> Self { Self } }
//! # Ok::<_, CommonError>(())
//! ```
//!
//! Converting from [`Move`] to [`UciMove`]:
//!
//! ```
//! # use shakmaty::{Square, Move, Role, Chess, Position, uci::UciMove};
//! #
//! let pos = Chess::default();
//!
//! let m = Move::Normal {
//!     role: Role::Knight,
//!     from: Square::B1,
//!     to: Square::C3,
//!     capture: None,
//!     promotion: None,
//! };
//!
//! let uci = m.to_uci(pos.castles().mode());
//! assert_eq!(uci.to_string(), "b1c3");
//!
//! let uci = UciMove::from_standard(m);
//! assert_eq!(uci.to_string(), "b1c3");
//!
//! let uci = UciMove::from_chess960(m);
//! assert_eq!(uci.to_string(), "b1c3");
//! ```
//!
//! [`Move`]: super::Move

use core::{error, fmt, str::FromStr};

use crate::{CastlingMode, CastlingSide, Move, Position, Rank, Role, Square, util::AppendAscii};

/// Error when parsing an invalid UCI move.
#[derive(Clone, Debug)]
pub struct ParseUciMoveError;

impl fmt::Display for ParseUciMoveError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("invalid uci")
    }
}

impl error::Error for ParseUciMoveError {}

/// Error when UCI move is illegal.
#[derive(Clone, Debug)]
pub struct IllegalUciMoveError;

impl fmt::Display for IllegalUciMoveError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("illegal uci")
    }
}

impl error::Error for IllegalUciMoveError {}

/// A move as represented in the UCI protocol.
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
pub enum UciMove {
    /// A normal move, e.g. `e2e4` or `h2h1q`.
    Normal {
        from: Square,
        to: Square,
        promotion: Option<Role>,
    },
    /// A piece drop, e.g. `Q@f7`.
    Put { role: Role, to: Square },
    /// A null move (`0000`).
    Null,
}

impl FromStr for UciMove {
    type Err = ParseUciMoveError;

    fn from_str(uci: &str) -> Result<UciMove, ParseUciMoveError> {
        UciMove::from_ascii(uci.as_bytes())
    }
}

impl fmt::Display for UciMove {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.append_to(f)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for UciMove {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        // Longest syntactically valid UCI move: a1a1q
        let mut s = arrayvec::ArrayString::<5>::new();
        let _ = self.append_to(&mut s);
        serializer.serialize_str(&s)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for UciMove {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct UciMoveVisitor;

        impl serde::de::Visitor<'_> for UciMoveVisitor {
            type Value = UciMove;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("UCI move string")
            }

            fn visit_str<E>(self, value: &str) -> Result<UciMove, E>
            where
                E: serde::de::Error,
            {
                value.parse().map_err(serde::de::Error::custom)
            }
        }

        deserializer.deserialize_str(UciMoveVisitor)
    }
}

impl UciMove {
    pub const fn is_normal(self) -> bool {
        matches!(self, UciMove::Normal { .. })
    }

    pub const fn is_put(self) -> bool {
        matches!(self, UciMove::Put { .. })
    }

    pub const fn is_null(self) -> bool {
        matches!(self, UciMove::Null)
    }

    pub const fn from(self) -> Option<Square> {
        match self {
            UciMove::Normal { from, .. } => Some(from),
            UciMove::Put { .. } | UciMove::Null => None,
        }
    }

    pub const fn to(self) -> Option<Square> {
        match self {
            UciMove::Normal { to, .. } | UciMove::Put { to, .. } => Some(to),
            UciMove::Null => None,
        }
    }

    pub const fn promotion(self) -> Option<Role> {
        match self {
            UciMove::Normal { promotion, .. } => promotion,
            UciMove::Put { .. } | UciMove::Null => None,
        }
    }

    pub const fn is_promotion(self) -> bool {
        matches!(
            self,
            UciMove::Normal {
                promotion: Some(_),
                ..
            }
        )
    }

    /// Parses a move in UCI notation.
    ///
    /// # Errors
    ///
    /// Returns [`ParseUciMoveError`] if `uci` is not syntactically valid.
    ///
    /// # Examples
    ///
    /// ```
    /// use shakmaty::{Square, uci::UciMove};
    ///
    /// let uci = UciMove::from_ascii(b"e4e5")?;
    ///
    /// assert_eq!(uci, UciMove::Normal {
    ///     from: Square::E4,
    ///     to: Square::E5,
    ///     promotion: None,
    /// });
    ///
    /// # Ok::<_, shakmaty::uci::ParseUciMoveError>(())
    /// ```
    pub const fn from_ascii(uci: &[u8]) -> Result<UciMove, ParseUciMoveError> {
        Ok(if uci.len() == 4 {
            if uci[0] == b'0' && uci[1] == b'0' && uci[2] == b'0' && uci[3] == b'0' {
                return Ok(UciMove::Null);
            } else if uci[1] == b'@' {
                let Some(role) = Role::from_char(uci[0] as char) else {
                    return Err(ParseUciMoveError);
                };
                let Ok(to) = Square::from_ascii(&[uci[2], uci[3]]) else {
                    return Err(ParseUciMoveError);
                };
                UciMove::Put { role, to }
            } else {
                let Ok(from) = Square::from_ascii(&[uci[0], uci[1]]) else {
                    return Err(ParseUciMoveError);
                };
                let Ok(to) = Square::from_ascii(&[uci[2], uci[3]]) else {
                    return Err(ParseUciMoveError);
                };
                UciMove::Normal {
                    from,
                    to,
                    promotion: None,
                }
            }
        } else if uci.len() == 5 {
            let Ok(from) = Square::from_ascii(&[uci[0], uci[1]]) else {
                return Err(ParseUciMoveError);
            };
            let Ok(to) = Square::from_ascii(&[uci[2], uci[3]]) else {
                return Err(ParseUciMoveError);
            };
            let Some(promotion) = Role::from_char(uci[4] as char) else {
                return Err(ParseUciMoveError);
            };
            UciMove::Normal {
                from,
                to,
                promotion: Some(promotion),
            }
        } else {
            return Err(ParseUciMoveError);
        })
    }

    /// Converts a move to UCI notation. Castling moves are represented as
    /// a move of the king to its new position.
    ///
    /// Warning: Using standard notation for castling moves in Chess960 may
    /// create moves that are illegal or moves that can be confused with
    /// king moves.
    ///
    /// # Examples
    ///
    /// ```
    /// use shakmaty::{Move, Square, uci::UciMove};
    ///
    /// let m = Move::Castle {
    ///     king: Square::E8,
    ///     rook: Square::H8,
    /// };
    ///
    /// let uci = UciMove::from_standard(m);
    /// assert_eq!(uci.to_string(), "e8g8");
    /// ```
    pub fn from_standard(m: Move) -> UciMove {
        match m {
            Move::Castle { king, rook } => {
                let side = CastlingSide::from_king_side(king < rook);
                UciMove::Normal {
                    from: king,
                    to: Square::from_coords(side.king_to_file(), king.rank()),
                    promotion: None,
                }
            }
            _ => UciMove::from_chess960(m),
        }
    }

    /// Converts a move to UCI notation. Castling moves are represented as
    /// a move of the king to the corresponding rook square, independently of
    /// the position.
    ///
    /// # Examples
    ///
    /// ```
    /// use shakmaty::{Move, Square, uci::UciMove};
    ///
    /// let m = Move::Castle {
    ///     king: Square::E8,
    ///     rook: Square::H8,
    /// };
    ///
    /// let uci = UciMove::from_chess960(m);
    /// assert_eq!(uci.to_string(), "e8h8");
    /// ```
    pub const fn from_chess960(m: Move) -> UciMove {
        match m {
            Move::Normal {
                from,
                to,
                promotion,
                ..
            } => UciMove::Normal {
                from,
                to,
                promotion,
            },
            Move::EnPassant { from, to, .. } => UciMove::Normal {
                from,
                to,
                promotion: None,
            },
            Move::Castle { king, rook } => UciMove::Normal {
                from: king,
                to: rook,
                promotion: None,
            }, // Chess960-style
            Move::Put { role, to } => UciMove::Put { role, to },
        }
    }

    /// See [`UciMove::from_standard()`] or [`UciMove::from_chess960()`].
    pub fn from_move(m: Move, mode: CastlingMode) -> UciMove {
        match mode {
            CastlingMode::Standard => UciMove::from_standard(m),
            CastlingMode::Chess960 => UciMove::from_chess960(m),
        }
    }

    /// Tries to convert the `Uci` to a legal [`Move`] in the context of a
    /// position.
    ///
    /// # Errors
    ///
    /// Returns [`IllegalUciMoveError`] if the move is not legal.
    ///
    /// [`Move`]: super::Move
    pub fn to_move<P: Position>(self, pos: &P) -> Result<Move, IllegalUciMoveError> {
        let candidate = match self {
            UciMove::Normal {
                from,
                to,
                promotion,
            } => {
                let role = pos.board().role_at(from).ok_or(IllegalUciMoveError)?;

                if promotion.is_some() && role != Role::Pawn {
                    return Err(IllegalUciMoveError);
                }

                if role == Role::King && (pos.castles().castling_rights() & pos.us()).contains(to) {
                    Move::Castle {
                        king: from,
                        rook: to,
                    }
                } else if role == Role::King
                    && from == pos.turn().fold_wb(Square::E1, Square::E8)
                    && to.rank() == pos.turn().fold_wb(Rank::First, Rank::Eighth)
                    && from.distance(to) == 2
                {
                    if from.file() < to.file() {
                        Move::Castle {
                            king: from,
                            rook: pos.turn().fold_wb(Square::H1, Square::H8),
                        }
                    } else {
                        Move::Castle {
                            king: from,
                            rook: pos.turn().fold_wb(Square::A1, Square::A8),
                        }
                    }
                } else if role == Role::Pawn
                    && from.file() != to.file()
                    && !pos.board().occupied().contains(to)
                {
                    Move::EnPassant { from, to }
                } else {
                    Move::Normal {
                        role,
                        from,
                        capture: pos.board().role_at(to),
                        to,
                        promotion,
                    }
                }
            }
            UciMove::Put { role, to } => Move::Put { role, to },
            UciMove::Null => return Err(IllegalUciMoveError),
        };

        if pos.is_legal(candidate) {
            Ok(candidate)
        } else {
            Err(IllegalUciMoveError)
        }
    }

    #[must_use]
    pub const fn to_mirrored(self) -> UciMove {
        match self {
            UciMove::Normal {
                from,
                to,
                promotion,
            } => UciMove::Normal {
                from: from.flip_vertical(),
                to: to.flip_vertical(),
                promotion,
            },
            UciMove::Put { role, to } => UciMove::Put {
                role,
                to: to.flip_vertical(),
            },
            UciMove::Null => UciMove::Null,
        }
    }

    fn append_to<W: AppendAscii>(self, f: &mut W) -> Result<(), W::Error> {
        match self {
            UciMove::Normal {
                from,
                to,
                promotion,
            } => {
                from.append_to(f)?;
                to.append_to(f)?;
                if let Some(promotion) = promotion {
                    f.append_ascii(promotion.char())?;
                }
            }
            UciMove::Put { role, to } => {
                f.append_ascii(role.upper_char())?;
                f.append_ascii('@')?;
                to.append_to(f)?;
            }
            UciMove::Null => {
                f.append_ascii('0')?;
                f.append_ascii('0')?;
                f.append_ascii('0')?;
                f.append_ascii('0')?;
            }
        }
        Ok(())
    }

    #[cfg(feature = "alloc")]
    pub fn append_to_string(self, s: &mut alloc::string::String) {
        let _ = self.append_to(s);
    }

    #[cfg(feature = "alloc")]
    pub fn append_ascii_to(self, buf: &mut alloc::vec::Vec<u8>) {
        let _ = self.append_to(buf);
    }
}

#[cfg(feature = "bincode")]
impl bincode::Encode for UciMove {
    fn encode<E: bincode::enc::Encoder>(
        &self,
        encoder: &mut E,
    ) -> Result<(), bincode::error::EncodeError> {
        crate::packed::PackedUciMove::pack(*self).encode(encoder)
    }
}

#[cfg(feature = "bincode")]
impl<Config> bincode::Decode<Config> for UciMove {
    fn decode<D: bincode::de::Decoder>(
        decoder: &mut D,
    ) -> Result<Self, bincode::error::DecodeError> {
        let packed = crate::packed::PackedUciMove::decode(decoder)?;
        Ok(packed.unpack())
    }
}

#[cfg(feature = "bincode")]
bincode::impl_borrow_decode!(UciMove);

impl Move {
    /// See [`UciMove::from_move()`].
    pub fn to_uci(self, mode: CastlingMode) -> UciMove {
        UciMove::from_move(self, mode)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Chess, fen::Fen};

    #[cfg(feature = "alloc")]
    #[test]
    #[cfg_attr(miri, ignore)]
    fn test_from_to_str() {
        use alloc::string::ToString as _;

        // Normal (no promotion)
        for from in Square::ALL {
            for to in Square::ALL {
                let uci = UciMove::Normal {
                    from,
                    to,
                    promotion: None,
                };
                assert_eq!(uci.to_string().parse::<UciMove>().expect("roundtrip"), uci);
            }
        }

        // Normal (promotion)
        for from in Square::ALL {
            for to in Square::ALL {
                for role in Role::ALL {
                    let uci = UciMove::Normal {
                        from,
                        to,
                        promotion: Some(role),
                    };
                    assert_eq!(uci.to_string().parse::<UciMove>().expect("roundtrip"), uci);
                }
            }
        }

        // Null
        assert_eq!(
            UciMove::Null
                .to_string()
                .parse::<UciMove>()
                .expect("roundtrip"),
            UciMove::Null
        );
    }

    #[test]
    fn test_uci_to_en_passant() {
        let mut pos = Chess::default();
        let e4 = "e2e4"
            .parse::<UciMove>()
            .expect("e4")
            .to_move(&pos)
            .expect("legal");
        pos.play_unchecked(e4);
        let nc6 = "b8c6"
            .parse::<UciMove>()
            .expect("Nc6")
            .to_move(&pos)
            .expect("legal");
        pos.play_unchecked(nc6);
        let e5 = "e4e5"
            .parse::<UciMove>()
            .expect("e5")
            .to_move(&pos)
            .expect("legal");
        pos.play_unchecked(e5);
        let d5 = "d7d5"
            .parse::<UciMove>()
            .expect("d5")
            .to_move(&pos)
            .expect("legal");
        pos.play_unchecked(d5);
        let exd5 = "e5d6"
            .parse::<UciMove>()
            .expect("exd6")
            .to_move(&pos)
            .expect("legal en passant");
        assert!(exd5.is_en_passant());
    }

    #[cfg(feature = "variant")]
    #[test]
    fn test_uci_to_crazyhouse() {
        use crate::position::variant::Crazyhouse;

        let mut pos = Crazyhouse::default();
        let e4 = "e2e4"
            .parse::<UciMove>()
            .expect("e4")
            .to_move(&pos)
            .expect("legal");
        pos.play_unchecked(e4);
        let d5 = "d7d5"
            .parse::<UciMove>()
            .expect("d5")
            .to_move(&pos)
            .expect("legal");
        pos.play_unchecked(d5);
        let exd5 = "e4d5"
            .parse::<UciMove>()
            .expect("exd5")
            .to_move(&pos)
            .expect("legal");
        pos.play_unchecked(exd5);
        let qxd5 = "d8d5"
            .parse::<UciMove>()
            .expect("Qxd5")
            .to_move(&pos)
            .expect("legal");
        pos.play_unchecked(qxd5);
        let p_at_d7 = "P@d7"
            .parse::<UciMove>()
            .expect("P@d7+")
            .to_move(&pos)
            .expect("legal");
        pos.play_unchecked(p_at_d7);
        assert!(pos.is_check());
    }

    #[test]
    fn test_king_captures_ummoved_rook() {
        let pos: Chess = "8/8/8/B2p3Q/2qPp1P1/b7/2P2PkP/4K2R b K - 0 1"
            .parse::<Fen>()
            .expect("valid fen")
            .into_position(CastlingMode::Standard)
            .expect("valid position");
        let uci = "g2h1".parse::<UciMove>().expect("valid uci");
        let m = uci.to_move(&pos).expect("legal uci");
        assert_eq!(
            m,
            Move::Normal {
                role: Role::King,
                from: Square::G2,
                capture: Some(Role::Rook),
                to: Square::H1,
                promotion: None,
            }
        );
    }

    #[cfg(feature = "alloc")]
    #[test]
    fn test_uci_to_castles() {
        use alloc::string::ToString as _;
        let mut pos: Chess = "nbqrknbr/pppppppp/8/8/8/8/PPPPPPPP/NBQRKNBR w KQkq - 0 1"
            .parse::<Fen>()
            .expect("valid fen")
            .into_position(CastlingMode::Chess960)
            .expect("valid position");
        for uci in &["f2f4", "d7d6", "f1g3", "c8g4", "g1f2", "e8d8", "e1g1"] {
            let m = uci
                .parse::<UciMove>()
                .expect("valid uci")
                .to_move(&pos)
                .expect("legal");
            pos.play_unchecked(m);
        }
        assert_eq!(
            Fen::from_position(&pos, crate::EnPassantMode::Legal).to_string(),
            "nbkr1nbr/ppp1pppp/3p4/8/5Pq1/6N1/PPPPPBPP/NBQR1RK1 b - - 5 4"
        );
    }
}