eschac 0.3.0

computing chess moves
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
//! Move representation.

use crate::array_vec::*;
use crate::bitboard::*;
use crate::board::*;
use crate::position::*;
use crate::san::*;
use crate::uci::*;

use core::convert::Infallible;
use core::iter::{ExactSizeIterator, FusedIterator};
use core::ops::ControlFlow;

/// A legal move.
#[must_use]
#[derive(Clone, Copy)]
pub struct Move<'l> {
    position: &'l Position,
    raw: RawMove,
}

impl<'l> Move<'l> {
    #[inline]
    pub(crate) unsafe fn new_unchecked(position: &'l Position, raw: RawMove) -> Self {
        Self { position, raw }
    }

    /// Returns the position after playing the move.
    ///
    /// This sets the en passant square after a double pawn advance, even when there is no pawn to
    /// capture or when capturing is not legal.
    #[inline]
    pub fn make(self) -> Position {
        let mut position = self.position.clone();
        unsafe { position.play_unchecked(self.raw) };
        position
    }

    /// Returns the position the move is played on.
    #[inline]
    pub fn position(self) -> &'l Position {
        self.position
    }

    /// Returns the type of piece that moves.
    #[inline]
    pub fn role(self) -> Role {
        self.raw.role()
    }

    /// Returns the origin square of the move.
    #[inline]
    pub fn from(self) -> Square {
        self.raw.from()
    }

    /// Returns the target square of the move.
    #[inline]
    pub fn to(self) -> Square {
        self.raw.to()
    }

    /// Returns the type of piece that the pawn is promoted to, if the move is a promotion.
    #[inline]
    pub fn promotion(self) -> Option<Role> {
        self.raw.promotion()
    }

    /// Returns `true` if the move is a capture.
    #[inline]
    pub fn is_capture(self) -> bool {
        let [p_b_q, n_b_k, r_q_k, _] = self.position.as_setup().bitboards;
        self.raw.kind == MoveType::EnPassant
            || !((p_b_q | n_b_k | r_q_k) & self.to().bitboard()).is_empty()
    }

    /// Returns the type of piece that is captured, if the move is a capture.
    #[inline]
    pub fn captured(self) -> Option<Role> {
        match self.raw.kind {
            MoveType::EnPassant => Some(Role::Pawn),
            _ => self.position.as_setup().role(self.raw.to),
        }
    }

    /// Returns the UCI notation of the move.
    #[inline]
    pub fn to_uci(self) -> UciMove {
        self.raw.uci()
    }

    /// Returns the standard algebraic notation of the move.
    pub fn to_san(self) -> San {
        struct MoveGenImpl<const ROLE: u8> {
            to: Bitboard,
            candidates: Bitboard,
        }
        impl<const ROLE: u8> MoveGenImpl<ROLE> {
            #[inline]
            fn new(to: Square) -> Self {
                Self {
                    to: to.bitboard(),
                    candidates: Bitboard::new(),
                }
            }
        }
        impl<const ROLE: u8> MoveGen<Infallible> for MoveGenImpl<ROLE> {
            #[inline]
            fn roles(&self, role: Role) -> bool {
                role as u8 == ROLE
            }
            #[inline]
            fn to(&self) -> Bitboard {
                self.to
            }
            #[inline]
            fn extend<I>(&mut self, iter: I) -> ControlFlow<Infallible>
            where
                I: Iterator<Item = RawMove> + ExactSizeIterator,
            {
                iter.for_each(|raw| {
                    debug_assert!(raw.role() as u8 == ROLE);
                    debug_assert!(self.to.contains(raw.to()));
                    self.candidates.insert(raw.from);
                });
                ControlFlow::Continue(())
            }
        }
        San {
            inner: match self.raw.kind {
                MoveType::CastleShort => SanInner::Castle(CastlingSide::Short),
                MoveType::CastleLong => SanInner::Castle(CastlingSide::Long),
                MoveType::PawnAdvance
                | MoveType::PawnAdvancePromotion
                | MoveType::PawnDoubleAdvance => SanInner::Normal {
                    role: Role::Pawn,
                    file: None,
                    rank: None,
                    capture: false,
                    target: self.to(),
                    promotion: self.promotion(),
                },
                MoveType::PawnAttack | MoveType::PawnAttackPromotion | MoveType::EnPassant => {
                    SanInner::Normal {
                        role: Role::Pawn,
                        file: Some(self.from().file()),
                        rank: None,
                        capture: true,
                        target: self.to(),
                        promotion: self.promotion(),
                    }
                }
                _ => {
                    fn aux<const ROLE: u8>(m: &Move) -> SanInner {
                        let mut moves = MoveGenImpl::<ROLE>::new(m.to());
                        let ControlFlow::Continue(()) = m.position().generate_moves(&mut moves);
                        let candidates = moves.candidates;
                        let (file, rank) = if candidates == m.from().bitboard() {
                            (None, None)
                        } else if candidates & m.from().file().bitboard() == m.from().bitboard() {
                            (Some(m.from().file()), None)
                        } else if candidates & m.from().rank().bitboard() == m.from().bitboard() {
                            (None, Some(m.from().rank()))
                        } else {
                            (Some(m.from().file()), Some(m.from().rank()))
                        };
                        SanInner::Normal {
                            role: m.role(),
                            file,
                            rank,
                            capture: m.is_capture(),
                            target: m.to(),
                            promotion: None,
                        }
                    }
                    match self.role() {
                        Role::Pawn => aux::<1>(&self),
                        Role::Knight => aux::<2>(&self),
                        Role::Bishop => aux::<3>(&self),
                        Role::Rook => aux::<4>(&self),
                        Role::Queen => aux::<5>(&self),
                        Role::King => aux::<6>(&self),
                    }
                }
            },
            suffix: {
                let pos = self.make();
                let mut moves = MateMoveGenImpl::new();
                let ControlFlow::Continue(()) = pos.generate_moves(&mut moves);
                let MateMoveGenImpl { is_check, is_mate } = moves;
                match (is_check, is_mate) {
                    (false, _) => None,
                    (true, false) => Some(SanSuffix::Check),
                    (true, true) => Some(SanSuffix::Checkmate),
                }
            },
        }
    }
}

/// The list of all the legal moves on a position. It is returned by [`Position::legal_moves`].
///
/// This type lies on the stack and has a fixed capacity of 218 moves, as there exists no reachable
/// position with more legal moves[^1].
///
/// [^1]: In 1964, Nenad Petrović published a
/// [composition](https://lichess.org/editor/R6R/3Q4/1Q4Q1/4Q3/2Q4Q/Q4Q2/pp1Q4/kBNN1KB1_w_-_-_0_1)
/// with 218 legal moves. 60 years later, this was proven to be optimal by
/// [Tobs40](https://lichess.org/@/Tobs40/blog/why-a-reachable-position-can-have-at-most-218-playable-moves/a5xdxeqs).
/// Even though the [`Position`] type can represent some unreachable positions the proof still
/// holds, as its definition of a position is even less restrictive.
#[must_use]
#[derive(Clone)]
pub struct Moves<'l> {
    position: &'l Position,
    is_check: bool,
    en_passant_is_legal: bool,
    array: ArrayVec<RawMove, 218>,
}

impl<'l> MoveGen<Infallible> for Moves<'l> {
    #[inline]
    fn is_check(&mut self) -> ControlFlow<Infallible> {
        self.is_check = true;
        ControlFlow::Continue(())
    }
    #[inline]
    fn en_passant_is_legal(&mut self) -> ControlFlow<Infallible> {
        self.en_passant_is_legal = true;
        ControlFlow::Continue(())
    }
    #[inline]
    fn extend<I>(&mut self, iter: I) -> ControlFlow<Infallible>
    where
        I: Iterator<Item = RawMove> + ExactSizeIterator,
    {
        iter.for_each(|raw| unsafe { self.array.push_unchecked(raw) });
        ControlFlow::Continue(())
    }
}

impl<'l> Moves<'l> {
    #[inline]
    pub(crate) fn compute(position: &'l Position) -> Moves<'l> {
        fn aux(position: &Position, moves: &mut Moves) {
            let ControlFlow::Continue(()) = position.generate_moves(moves);
        }
        let mut moves = Moves {
            position,
            is_check: false,
            en_passant_is_legal: false,
            array: ArrayVec::new(),
        };
        aux(position, &mut moves);
        moves
    }

    /// Returns the position on which the moves are played.
    #[inline]
    pub fn position(&self) -> &Position {
        self.position
    }

    /// Iterates over the moves.
    #[inline]
    pub fn iter(&'l self) -> MovesIter<'l> {
        MovesIter {
            position: self.position,
            iter: self.array.as_slice().into_iter(),
        }
    }

    /// Returns the number of moves in the list.
    #[inline]
    pub fn len(&self) -> usize {
        self.array.len()
    }

    /// Returns `true` if the king is in check.
    #[inline]
    pub fn is_check(&self) -> bool {
        self.is_check
    }

    /// Returns `true` if there is no legal move on the position.
    #[inline]
    pub fn is_mate(&self) -> bool {
        self.array.len() == 0
    }

    /// Returns `true` if taking en passant is legal on the position.
    #[inline]
    pub fn en_passant_is_legal(&self) -> bool {
        self.en_passant_is_legal
    }

    /// Returns the move at the given index, if it exists.
    #[inline]
    pub fn get(&self, index: usize) -> Option<Move<'l>> {
        self.array.get(index).copied().map(|raw| Move {
            position: self.position,
            raw,
        })
    }

    /// Sorts the list in ascending order with a comparison function, preserving initial order of
    /// equal elements. See `std::slice::sort_by` for details.
    #[inline]
    pub fn sort_by<F>(&mut self, mut compare: F)
    where
        F: FnMut(Move, Move) -> core::cmp::Ordering,
    {
        self.array.as_mut_slice().sort_by(|a, b| {
            compare(
                Move {
                    position: self.position,
                    raw: *a,
                },
                Move {
                    position: self.position,
                    raw: *b,
                },
            )
        });
    }

    /// Sorts the list in ascending order with a comparison function, **without** preserving the
    /// initial order of equal elements. See [`sort_unstable_by`](`slice::sort_unstable_by`) for
    /// details.
    #[inline]
    pub fn sort_unstable_by<F>(&mut self, mut compare: F)
    where
        F: FnMut(Move, Move) -> core::cmp::Ordering,
    {
        self.array.as_mut_slice().sort_unstable_by(|a, b| {
            compare(
                Move {
                    position: self.position,
                    raw: *a,
                },
                Move {
                    position: self.position,
                    raw: *b,
                },
            )
        });
    }
}

/// An iterator over legal moves.
#[derive(Clone)]
pub struct MovesIter<'l> {
    position: &'l Position,
    iter: core::slice::Iter<'l, RawMove>,
}
impl<'l> Iterator for MovesIter<'l> {
    type Item = Move<'l>;
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next().map(|raw| Move {
            position: self.position,
            raw: *raw,
        })
    }
}
impl<'l> FusedIterator for MovesIter<'l> {}
impl<'l> ExactSizeIterator for MovesIter<'l> {
    #[inline]
    fn len(&self) -> usize {
        self.iter.len()
    }
}
impl<'l> IntoIterator for &'l Moves<'l> {
    type Item = Move<'l>;
    type IntoIter = MovesIter<'l>;
    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// An iterator over legal moves.
pub struct MovesIntoIter<'l> {
    position: &'l Position,
    iter: ArrayVecIntoIter<RawMove, 218>,
}
impl<'l> Iterator for MovesIntoIter<'l> {
    type Item = Move<'l>;
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next().map(|raw| Move {
            position: self.position,
            raw,
        })
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}
impl<'l> FusedIterator for MovesIntoIter<'l> {}
impl<'l> ExactSizeIterator for MovesIntoIter<'l> {
    #[inline]
    fn len(&self) -> usize {
        self.iter.len()
    }
}
impl<'l> IntoIterator for Moves<'l> {
    type Item = Move<'l>;
    type IntoIter = MovesIntoIter<'l>;
    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        MovesIntoIter {
            position: self.position,
            iter: self.array.into_iter(),
        }
    }
}