lazychess 0.1.2

A fast, memory-efficient chess engine library for Rust
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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
use crate::board::Board;
use crate::types::*;

const FILE_A: u64 = 0x0101010101010101;
const FILE_H: u64 = 0x8080808080808080;

const RANK_1: u64 = 0x00000000000000FF;
const RANK_3: u64 = 0x0000000000FF0000;
const RANK_6: u64 = 0x0000FF0000000000;
const RANK_8: u64 = 0xFF00000000000000;

/// Computes knight attack squares for a given square at compile time.
///
/// Used to populate the `KNIGHT_ATTACKS` static table; not called at runtime.
const fn knight_attacks_sq(sq: u8) -> u64 {
    let r = (sq / 8) as i32;
    let f = (sq % 8) as i32;
    let mut bb: u64 = 0;
    if r + 2 < 8 && f + 1 < 8 {
        bb |= 1u64 << ((r + 2) * 8 + f + 1) as u32;
    }
    if r + 2 < 8 && f > 0 {
        bb |= 1u64 << ((r + 2) * 8 + f - 1) as u32;
    }
    if r - 2 >= 0 && f + 1 < 8 {
        bb |= 1u64 << ((r - 2) * 8 + f + 1) as u32;
    }
    if r - 2 >= 0 && f > 0 {
        bb |= 1u64 << ((r - 2) * 8 + f - 1) as u32;
    }
    if r + 1 < 8 && f + 2 < 8 {
        bb |= 1u64 << ((r + 1) * 8 + f + 2) as u32;
    }
    if r + 1 < 8 && f - 2 >= 0 {
        bb |= 1u64 << ((r + 1) * 8 + f - 2) as u32;
    }
    if r > 0 && f + 2 < 8 {
        bb |= 1u64 << ((r - 1) * 8 + f + 2) as u32;
    }
    if r > 0 && f - 2 >= 0 {
        bb |= 1u64 << ((r - 1) * 8 + f - 2) as u32;
    }
    bb
}

/// Computes king attack squares for a given square at compile time.
///
/// Used to populate the `KING_ATTACKS` static table; not called at runtime.
const fn king_attacks_sq(sq: u8) -> u64 {
    let r = (sq / 8) as i32;
    let f = (sq % 8) as i32;
    let mut bb: u64 = 0;
    if r + 1 < 8 && f > 0 {
        bb |= 1u64 << ((r + 1) * 8 + f - 1) as u32;
    }
    if r + 1 < 8 {
        bb |= 1u64 << ((r + 1) * 8 + f) as u32;
    }
    if r + 1 < 8 && f + 1 < 8 {
        bb |= 1u64 << ((r + 1) * 8 + f + 1) as u32;
    }
    if f > 0 {
        bb |= 1u64 << (r * 8 + f - 1) as u32;
    }
    if f + 1 < 8 {
        bb |= 1u64 << (r * 8 + f + 1) as u32;
    }
    if r > 0 && f > 0 {
        bb |= 1u64 << ((r - 1) * 8 + f - 1) as u32;
    }
    if r > 0 {
        bb |= 1u64 << ((r - 1) * 8 + f) as u32;
    }
    if r > 0 && f + 1 < 8 {
        bb |= 1u64 << ((r - 1) * 8 + f + 1) as u32;
    }
    bb
}

static KNIGHT_ATTACKS: [u64; 64] = {
    let mut t = [0u64; 64];
    let mut i = 0u8;
    while i < 64 {
        t[i as usize] = knight_attacks_sq(i);
        i += 1;
    }
    t
};

static KING_ATTACKS: [u64; 64] = {
    let mut t = [0u64; 64];
    let mut i = 0u8;
    while i < 64 {
        t[i as usize] = king_attacks_sq(i);
        i += 1;
    }
    t
};

/// All squares attacked by white pawns on `pawns`.
///
/// << 9 with !FILE_A: northeast diagonal — we mask FILE_A because an h-file
/// pawn shifted left by 9 would wrap around to the a-file of the next rank.
/// << 7 with !FILE_H: northwest diagonal — same idea but for the a-file pawn
/// wrapping to h-file.
#[inline(always)]
fn white_pawn_attacks(pawns: u64) -> u64 {
    ((pawns << 9) & !FILE_A) | ((pawns << 7) & !FILE_H)
}

/// All squares attacked by black pawns on `pawns`.
///
/// >> 7 with !FILE_A: southeast diagonal (toward h-file from black's POV).
/// >> 9 with !FILE_H: southwest diagonal. Same wrap-around logic as white.
#[inline(always)]
fn black_pawn_attacks(pawns: u64) -> u64 {
    ((pawns >> 7) & !FILE_A) | ((pawns >> 9) & !FILE_H)
}

/// Classical ray-casting rook attacks from `sq` against the given occupancy.
///
/// Slides outward in all four orthogonal directions, stopping at (and
/// including) the first occupied square in each direction.
#[inline]
fn rook_attacks(sq: Square, occupied: u64) -> u64 {
    let mut attacks = 0u64;
    let rank = (sq / 8) as i32;
    let file = (sq % 8) as i32;

    macro_rules! ray {
        ($dr:expr, $df:expr) => {{
            let (mut r, mut f) = (rank + $dr, file + $df);
            while (0..8).contains(&r) && (0..8).contains(&f) {
                let bit = 1u64 << (r * 8 + f);
                attacks |= bit;
                if occupied & bit != 0 {
                    break;
                }
                r += $dr;
                f += $df;
            }
        }};
    }
    ray!(1, 0);
    ray!(-1, 0);
    ray!(0, 1);
    ray!(0, -1);
    attacks
}

/// Classical ray-casting bishop attacks from `sq` against the given occupancy.
///
/// Slides outward in all four diagonal directions, stopping at (and
/// including) the first occupied square in each direction.
#[inline]
fn bishop_attacks(sq: Square, occupied: u64) -> u64 {
    let mut attacks = 0u64;
    let rank = (sq / 8) as i32;
    let file = (sq % 8) as i32;

    macro_rules! ray {
        ($dr:expr, $df:expr) => {{
            let (mut r, mut f) = (rank + $dr, file + $df);
            while (0..8).contains(&r) && (0..8).contains(&f) {
                let bit = 1u64 << (r * 8 + f);
                attacks |= bit;
                if occupied & bit != 0 {
                    break;
                }
                r += $dr;
                f += $df;
            }
        }};
    }
    ray!(1, 1);
    ray!(1, -1);
    ray!(-1, 1);
    ray!(-1, -1);
    attacks
}

/// Returns `true` if `sq` is attacked by any piece belonging to `by_color`.
pub fn is_square_attacked(board: &Board, sq: Square, by_color: Color) -> bool {
    let occ = board.all_occupancy();
    let bi = by_color.index();

    // Knights
    if KNIGHT_ATTACKS[sq as usize] & board.bb[bi][PieceType::Knight.index()] != 0 {
        return true;
    }
    // King
    if KING_ATTACKS[sq as usize] & board.bb[bi][PieceType::King.index()] != 0 {
        return true;
    }
    // Diagonal sliders (bishop + queen)
    let diag = board.bb[bi][PieceType::Bishop.index()] | board.bb[bi][PieceType::Queen.index()];
    if bishop_attacks(sq, occ) & diag != 0 {
        return true;
    }
    // Straight sliders (rook + queen)
    let straight = board.bb[bi][PieceType::Rook.index()] | board.bb[bi][PieceType::Queen.index()];
    if rook_attacks(sq, occ) & straight != 0 {
        return true;
    }
    // Pawns — we ask "which squares does a `by_color` pawn attack?" and check
    // whether `sq` is one of them.
    let their_pawns = board.bb[bi][PieceType::Pawn.index()];
    let pawn_atk = match by_color {
        Color::White => white_pawn_attacks(their_pawns),
        Color::Black => black_pawn_attacks(their_pawns),
    };
    if pawn_atk & (1u64 << sq) != 0 {
        return true;
    }

    false
}

/// Returns `true` if the king of `color` is currently in check.
pub fn is_in_check(board: &Board, color: Color) -> bool {
    board
        .king_square(color)
        .map(|sq| is_square_attacked(board, sq, color.opposite()))
        .unwrap_or(false)
}

/// Pushes all four promotion variants (Q, R, B, N) for a pawn moving
/// from `from` to `to` onto `moves`.
#[inline]
fn push_promotions(from: Square, to: Square, moves: &mut Vec<Move>) {
    for &pt in &[
        PieceType::Queen,
        PieceType::Rook,
        PieceType::Bishop,
        PieceType::Knight,
    ] {
        moves.push(Move::with_flag(from, to, MoveFlag::Promotion(pt)));
    }
}

/// Expands a target bitboard into individual `Move` entries appended to `moves`.
///
/// Despite the general name, callers pass `targets & not_our` — meaning this
/// handles both quiet moves and captures in one shot. Separating them here
/// would require two loops over the same bitboard for no speed benefit, since
/// move legality is checked later in `generate_legal_moves` anyway.
#[inline]
fn add_moves(from: Square, mut targets: u64, moves: &mut Vec<Move>) {
    while targets != 0 {
        let to = targets.trailing_zeros() as Square;
        targets &= targets - 1;
        moves.push(Move::new(from, to));
    }
}

/// Generates all pseudo-legal pawn moves for `us` and appends them to `moves`.
///
/// Covers single and double pushes, diagonal captures, en-passant captures,
/// and all promotion variants for both colours.
fn gen_pawn_moves(board: &Board, us: Color, their: u64, empty: u64, moves: &mut Vec<Move>) {
    let pawns = board.piece_bb(us, PieceType::Pawn);
    let ep_bit = board.en_passant.map_or(0u64, |sq| 1u64 << sq);

    // we include the ep square in capture targets so the bitboard shift
    // naturally lands on it without a separate special-case branch below.
    let captures_to = their | ep_bit;

    match us {
        Color::White => {
            let single = (pawns << 8) & empty;
            let double = ((single & RANK_3) << 8) & empty;
            let cap_r = (pawns << 9) & !FILE_A & captures_to;
            let cap_l = (pawns << 7) & !FILE_H & captures_to;

            // Single pushes (non-promo)
            let mut bb = single & !RANK_8;
            while bb != 0 {
                let to = bb.trailing_zeros() as Square;
                bb &= bb - 1;
                moves.push(Move::new(to - 8, to));
            }
            // Double pushes
            let mut bb = double;
            while bb != 0 {
                let to = bb.trailing_zeros() as Square;
                bb &= bb - 1;
                moves.push(Move::with_flag(to - 16, to, MoveFlag::DoublePawnPush));
            }
            // Promotions (push)
            let mut bb = single & RANK_8;
            while bb != 0 {
                let to = bb.trailing_zeros() as Square;
                bb &= bb - 1;
                push_promotions(to - 8, to, moves);
            }
            // Captures right (non-promo)
            let mut bb = cap_r & !RANK_8;
            while bb != 0 {
                let to = bb.trailing_zeros() as Square;
                bb &= bb - 1;
                let from = to - 9;
                // ep_bit >> to isolates the ep bit relative to `to`; it is 1
                // iff `to` is exactly the en-passant square.
                if ep_bit >> to & 1 != 0 {
                    moves.push(Move::with_flag(from, to, MoveFlag::EnPassant));
                } else {
                    moves.push(Move::new(from, to));
                }
            }
            // Captures left (non-promo)
            let mut bb = cap_l & !RANK_8;
            while bb != 0 {
                let to = bb.trailing_zeros() as Square;
                bb &= bb - 1;
                let from = to - 7;
                if ep_bit >> to & 1 != 0 {
                    moves.push(Move::with_flag(from, to, MoveFlag::EnPassant));
                } else {
                    moves.push(Move::new(from, to));
                }
            }
            // Promo captures right
            let mut bb = cap_r & RANK_8;
            while bb != 0 {
                let to = bb.trailing_zeros() as Square;
                bb &= bb - 1;
                push_promotions(to - 9, to, moves);
            }
            // Promo captures left
            let mut bb = cap_l & RANK_8;
            while bb != 0 {
                let to = bb.trailing_zeros() as Square;
                bb &= bb - 1;
                push_promotions(to - 7, to, moves);
            }
        }

        Color::Black => {
            let single = (pawns >> 8) & empty;
            let double = ((single & RANK_6) >> 8) & empty;
            let cap_r = (pawns >> 7) & !FILE_A & captures_to;
            let cap_l = (pawns >> 9) & !FILE_H & captures_to;

            // Single pushes (non-promo)
            let mut bb = single & !RANK_1;
            while bb != 0 {
                let to = bb.trailing_zeros() as Square;
                bb &= bb - 1;
                moves.push(Move::new(to + 8, to));
            }
            // Double pushes
            let mut bb = double;
            while bb != 0 {
                let to = bb.trailing_zeros() as Square;
                bb &= bb - 1;
                moves.push(Move::with_flag(to + 16, to, MoveFlag::DoublePawnPush));
            }
            // Promotions (push)
            let mut bb = single & RANK_1;
            while bb != 0 {
                let to = bb.trailing_zeros() as Square;
                bb &= bb - 1;
                push_promotions(to + 8, to, moves);
            }
            // Captures right (non-promo) — toward a-file for black
            let mut bb = cap_r & !RANK_1;
            while bb != 0 {
                let to = bb.trailing_zeros() as Square;
                bb &= bb - 1;
                let from = to + 7;
                if ep_bit >> to & 1 != 0 {
                    moves.push(Move::with_flag(from, to, MoveFlag::EnPassant));
                } else {
                    moves.push(Move::new(from, to));
                }
            }
            // Captures left (non-promo) — toward h-file for black
            let mut bb = cap_l & !RANK_1;
            while bb != 0 {
                let to = bb.trailing_zeros() as Square;
                bb &= bb - 1;
                let from = to + 9;
                if ep_bit >> to & 1 != 0 {
                    moves.push(Move::with_flag(from, to, MoveFlag::EnPassant));
                } else {
                    moves.push(Move::new(from, to));
                }
            }
            // Promo captures right
            let mut bb = cap_r & RANK_1;
            while bb != 0 {
                let to = bb.trailing_zeros() as Square;
                bb &= bb - 1;
                push_promotions(to + 7, to, moves);
            }
            // Promo captures left
            let mut bb = cap_l & RANK_1;
            while bb != 0 {
                let to = bb.trailing_zeros() as Square;
                bb &= bb - 1;
                push_promotions(to + 9, to, moves);
            }
        }
    }
}

/// Appends castling moves for `color` if the rights and vacancy conditions are
/// met.
///
/// Does **not** check whether the king passes through check — that is deferred
/// to [`generate_legal_moves`].
fn gen_castling(board: &Board, king_sq: Square, color: Color, moves: &mut Vec<Move>) {
    let occ = board.all_occupancy();
    match color {
        Color::White => {
            if king_sq != 4 {
                return;
            }
            // f1 (5), g1 (6) must be empty
            if board.castling_rights.white_kingside && occ & 0x0000000000000060 == 0 {
                moves.push(Move::with_flag(4, 6, MoveFlag::CastleKingside));
            }
            // b1 (1), c1 (2), d1 (3) must be empty
            if board.castling_rights.white_queenside && occ & 0x000000000000000E == 0 {
                moves.push(Move::with_flag(4, 2, MoveFlag::CastleQueenside));
            }
        }
        Color::Black => {
            if king_sq != 60 {
                return;
            }
            // f8 (61), g8 (62) must be empty
            if board.castling_rights.black_kingside && occ & 0x6000000000000000 == 0 {
                moves.push(Move::with_flag(60, 62, MoveFlag::CastleKingside));
            }
            // b8 (57), c8 (58), d8 (59) must be empty
            if board.castling_rights.black_queenside && occ & 0x0E00000000000000 == 0 {
                moves.push(Move::with_flag(60, 58, MoveFlag::CastleQueenside));
            }
        }
    }
}

/// Generates all pseudo-legal moves for the side to move.
///
/// *Pseudo-legal* means moves that respect each piece's movement rules but may
/// leave the king in check. Filtering for full legality is done in
/// [`generate_legal_moves`].
pub fn generate_pseudo_legal_moves(board: &Board) -> Vec<Move> {
    let mut moves: Vec<Move> = Vec::with_capacity(48);
    let us = board.side_to_move;
    let occ = board.all_occupancy();
    let our = board.occupancy(us);
    let their = board.occupancy(us.opposite());
    let empty = !occ;
    let not_our = !our;

    gen_pawn_moves(board, us, their, empty, &mut moves);

    // Knights
    let mut bb = board.piece_bb(us, PieceType::Knight);
    while bb != 0 {
        let from = bb.trailing_zeros() as Square;
        bb &= bb - 1;
        // not_our includes enemy squares, so this naturally generates captures too.
        add_moves(from, KNIGHT_ATTACKS[from as usize] & not_our, &mut moves);
    }

    // Bishops
    let mut bb = board.piece_bb(us, PieceType::Bishop);
    while bb != 0 {
        let from = bb.trailing_zeros() as Square;
        bb &= bb - 1;
        add_moves(from, bishop_attacks(from, occ) & not_our, &mut moves);
    }

    // Rooks
    let mut bb = board.piece_bb(us, PieceType::Rook);
    while bb != 0 {
        let from = bb.trailing_zeros() as Square;
        bb &= bb - 1;
        add_moves(from, rook_attacks(from, occ) & not_our, &mut moves);
    }

    // Queens
    let mut bb = board.piece_bb(us, PieceType::Queen);
    while bb != 0 {
        let from = bb.trailing_zeros() as Square;
        bb &= bb - 1;
        let atk = (bishop_attacks(from, occ) | rook_attacks(from, occ)) & not_our;
        add_moves(from, atk, &mut moves);
    }

    // King
    let king_sq = board.king_square(us).unwrap_or(64);
    if king_sq < 64 {
        add_moves(
            king_sq,
            KING_ATTACKS[king_sq as usize] & not_our,
            &mut moves,
        );
        gen_castling(board, king_sq, us, &mut moves);
    }

    moves
}

/// Applies `mv` to `board` and returns the resulting board state.
///
/// All bitboard updates (captures, castling rook moves, en-passant removal,
/// promotions, castling-rights stripping) are handled here on the hot path
/// without any `piece_at` lookups.
pub fn apply_move(board: &Board, mv: &Move) -> Board {
    let mut nb = board.clone();
    let us = board.side_to_move;
    let them = us.opposite();
    let ui = us.index();
    let ti = them.index();
    let bit_from = 1u64 << mv.from;
    let bit_to = 1u64 << mv.to;

    // Identify the moving piece type (O(6), us only).
    let mut pt_idx = 0usize;
    for pi in 0..6usize {
        if nb.bb[ui][pi] & bit_from != 0 {
            pt_idx = pi;
            break;
        }
    }
    let pt = PieceType::from_index(pt_idx);

    // Half-move clock: reset on pawn moves or captures.
    let is_capture =
        board.bb[ti].iter().any(|&bb| bb & bit_to != 0) || mv.flag == MoveFlag::EnPassant;
    if is_capture || pt == PieceType::Pawn {
        nb.halfmove_clock = 0;
    } else {
        nb.halfmove_clock += 1;
    }

    // En passant target (only valid for double pawn pushes).
    nb.en_passant = if mv.flag == MoveFlag::DoublePawnPush {
        Some(if us == Color::White {
            mv.to - 8
        } else {
            mv.to + 8
        })
    } else {
        None
    };

    // Remove the moving piece from its source square.
    nb.bb[ui][pt_idx] &= !bit_from;

    match &mv.flag {
        MoveFlag::EnPassant => {
            // The captured pawn is not at mv.to but one rank behind it.
            let cap_sq = if us == Color::White {
                mv.to - 8
            } else {
                mv.to + 8
            };
            nb.bb[ti][PieceType::Pawn.index()] &= !(1u64 << cap_sq);
            nb.bb[ui][pt_idx] |= bit_to;
        }

        MoveFlag::CastleKingside => {
            let (rook_from, rook_to) = match us {
                Color::White => (7u8, 5u8),
                Color::Black => (63u8, 61u8),
            };
            nb.bb[ui][PieceType::Rook.index()] ^= (1u64 << rook_from) | (1u64 << rook_to);
            // we don't need to clear enemy pieces at bit_to here — castling
            // is only generated when the transit and destination squares are
            // empty, so there is nothing to capture.
            nb.bb[ui][pt_idx] |= bit_to;
        }

        MoveFlag::CastleQueenside => {
            let (rook_from, rook_to) = match us {
                Color::White => (0u8, 3u8),
                Color::Black => (56u8, 59u8),
            };
            nb.bb[ui][PieceType::Rook.index()] ^= (1u64 << rook_from) | (1u64 << rook_to);
            // same reasoning as CastleKingside above.
            nb.bb[ui][pt_idx] |= bit_to;
        }

        MoveFlag::Promotion(promo_type) => {
            // Clear any captured enemy piece at the destination.
            for pi in 0..6usize {
                nb.bb[ti][pi] &= !bit_to;
            }
            strip_castling_on_capture(&mut nb, mv.to);
            // Place promoted piece (not the original pawn type).
            nb.bb[ui][promo_type.index()] |= bit_to;
            // pt is Pawn here, so strip_castling_on_move is a no-op — but we
            // call it anyway for consistency in case pt ever changes.
            strip_castling_on_move(&mut nb, mv.from, pt, us);
            nb.side_to_move = them;
            if us == Color::Black {
                nb.fullmove_number += 1;
            }
            return nb;
        }

        MoveFlag::Normal | MoveFlag::DoublePawnPush => {
            // Clear any captured enemy piece.
            for pi in 0..6usize {
                nb.bb[ti][pi] &= !bit_to;
            }
            strip_castling_on_capture(&mut nb, mv.to);
            nb.bb[ui][pt_idx] |= bit_to;
        }
    }

    strip_castling_on_move(&mut nb, mv.from, pt, us);
    nb.side_to_move = them;
    if us == Color::Black {
        nb.fullmove_number += 1;
    }
    nb
}

/// Revokes castling rights when a rook's starting square is captured.
fn strip_castling_on_capture(board: &mut Board, to: Square) {
    match to {
        0 => board.castling_rights.white_queenside = false,
        7 => board.castling_rights.white_kingside = false,
        56 => board.castling_rights.black_queenside = false,
        63 => board.castling_rights.black_kingside = false,
        _ => {}
    }
}

/// Revokes castling rights when a king or rook moves away from its home square.
///
/// We take `us` explicitly rather than reading `board.side_to_move` because
/// at the call site `board.side_to_move` has not yet been flipped to `them`.
/// Passing `us` makes the dependency clear and keeps this function safe to
/// call at any point in `apply_move`, regardless of when the flip happens.
fn strip_castling_on_move(board: &mut Board, from: Square, pt: PieceType, us: Color) {
    match (us, pt) {
        (Color::White, PieceType::King) => {
            board.castling_rights.white_kingside = false;
            board.castling_rights.white_queenside = false;
        }
        (Color::Black, PieceType::King) => {
            board.castling_rights.black_kingside = false;
            board.castling_rights.black_queenside = false;
        }
        (Color::White, PieceType::Rook) => {
            if from == 0 {
                board.castling_rights.white_queenside = false;
            } else if from == 7 {
                board.castling_rights.white_kingside = false;
            }
        }
        (Color::Black, PieceType::Rook) => {
            if from == 56 {
                board.castling_rights.black_queenside = false;
            } else if from == 63 {
                board.castling_rights.black_kingside = false;
            }
        }
        _ => {}
    }
}

/// Generates all *legal* moves for the side to move.
///
/// Filters the pseudo-legal move list by:
/// - Rejecting moves that leave the king in check.
/// - For castling, additionally verifying the king does not start in check and
///   does not pass through an attacked square.
///
/// Note: the destination square check for castling is covered by the final
/// `!is_in_check` call — the king ends up there, so if it were attacked the
/// check would be detected automatically.
pub fn generate_legal_moves(board: &Board) -> Vec<Move> {
    let color = board.side_to_move;
    generate_pseudo_legal_moves(board)
        .into_iter()
        .filter(|mv| {
            match mv.flag {
                MoveFlag::CastleKingside => {
                    if is_in_check(board, color) {
                        return false;
                    }
                    // King passes through mv.from + 1 (f1 / f8).
                    if is_square_attacked(board, mv.from + 1, color.opposite()) {
                        return false;
                    }
                }
                MoveFlag::CastleQueenside => {
                    if is_in_check(board, color) {
                        return false;
                    }
                    // King passes through mv.from - 1 (d1 / d8).
                    if is_square_attacked(board, mv.from - 1, color.opposite()) {
                        return false;
                    }
                }
                _ => {}
            }
            let new_board = apply_move(board, mv);
            !is_in_check(&new_board, color)
        })
        .collect()
}