laura_core 0.4.0

A fast and efficient move generator for chess engines.
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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
/*
    Laura-Core: a fast and efficient move generator for chess engines.

    Copyright (C) 2024-2025 HansTibberio <hanstiberio@proton.me>

    Laura-Core is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Laura-Core is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Laura-Core. If not, see <https://www.gnu.org/licenses/>.
*/

use crate::get_king_attacks;
use crate::get_knight_attacks;
use crate::get_pawn_attacks;
use crate::{DESTINATION, KING_SIDE, MEDIUM, PRESENCE, QUEEN_SIDE, SOURCE};
use crate::{get_between, get_bishop_rays, get_rook_rays};
use crate::{get_bishop_attacks, get_rook_attacks};

use crate::{BitBoard, Board, Call_Handler, Enumerate_Moves, Move, MoveList, MoveType, Square};

// This file is responsible for generating legal moves for pieces, which is a core
// part of the chess engine's functionality. It works with bitboards and evaluates
// possible moves based on the current game state.
//
// This version of the move generation code has been adapted from the chess engine Belette.
// with en passant move generation inspired by Cozy-Chess.
//
// This file contains code licensed under GPLv3 and MIT.
// - Belette (GPLv3): https://github.com/vincentbab/Belette/blob/main/src/movegen.h
// - Cozy-Chess (MIT): https://github.com/analog-hors/cozy-chess/blob/master/cozy-chess/src/board/movegen/mod.rs

/// A move filter that includes only quiet moves (non-captures and non-promotions).
///
/// This filter is typically used during positional search phases where
/// non-tactical moves are prioritized to reduce the branching factor.
pub struct QuietMoves {}

/// A move filter that includes only tactical moves (captures and queen promotions).
///
/// This filter is useful for tactical search phases, such as quiescence search
/// or move ordering based on high-impact moves.
pub struct TacticalMoves {}

/// A move filter that includes all legal moves (quiet and tactical).
///
/// This is the default filter used for generating the complete list of legal moves.
pub struct AllMoves {}

/// A trait for filtering move types during move generation.
///
/// Implementors of this trait specify which categories of moves should be included
/// when generating moves. This allows for fine-grained control over the types
/// of moves generated by the engine.
///
/// The `QUIETS` constant indicates whether to include quiet moves (non-captures),
/// and the `TACTICALS` constant indicates whether to include tactical moves
/// (captures and promotions).
pub trait MoveFilter {
    /// Whether to include quiet moves (non-captures and non-promotions).
    const QUIETS: bool;
    /// Whether to include tactical moves (captures and promotions).
    const TACTICALS: bool;
}

impl MoveFilter for QuietMoves {
    const QUIETS: bool = true;
    const TACTICALS: bool = false;
}

impl MoveFilter for TacticalMoves {
    const QUIETS: bool = false;
    const TACTICALS: bool = true;
}

impl MoveFilter for AllMoves {
    const QUIETS: bool = true;
    const TACTICALS: bool = true;
}

/// Generates a list of legal moves for the given board based on the specified move filter.
///
/// This function enumerates all legal moves for the provided [`Board`] according to the move
/// types defined by the [`MoveFilter`] implementation `M`. The resulting moves are collected
/// into a [`MoveList`] and returned.
///
/// Internally, this function delegates to [`enumerate_legal_moves`] and uses a closure to
/// collect each move into the list.
///
/// # Example
/// ```
/// # use laura_core::*;
/// let board = Board::default();
/// let moves: MoveList = gen_moves::<AllMoves>(&board);
/// assert!(!moves.is_empty());
/// ```
#[inline(always)]
pub fn gen_moves<M: MoveFilter>(board: &Board) -> MoveList {
    let mut move_list: MoveList = MoveList::default();
    enumerate_legal_moves::<M, _>(board, |mv| -> bool {
        move_list.push(mv);
        true
    });
    move_list
}

/// Enumerates all legal moves for the given board and passes them to a handler function.
///
/// This function generates legal moves for the current board position based on the move
/// filter `M`. Each legal move is passed to the provided `handler` function.
///
/// The move enumeration accounts for checks, pins (diagonal and linear), castling rights,
/// and king safety. In positions with no checkers, both normal moves and castling are considered.
/// In positions with a single checker, only evasion moves are generated. In double check positions,
/// only king moves are legal.
///
/// # Example
/// ```
/// # use laura_core::*;
/// let board = Board::default();
/// let mut moves = vec![];
/// enumerate_legal_moves::<AllMoves, _>(&board, |m: Move| {
///     moves.push(m);
///     true // Continue enumeration
/// });
/// assert!(!moves.is_empty());
/// ```
#[inline(always)]
pub fn enumerate_legal_moves<M, F>(board: &Board, mut handler: F) -> bool
where
    M: MoveFilter,
    F: FnMut(Move) -> bool,
{
    let (diagonal_pins, linear_pins) = pinners(board);
    match board.checkers.count_bits() {
        0 => {
            Enumerate_Moves!(false, board, diagonal_pins, linear_pins, handler);
            if M::QUIETS {
                enumerate_castling_moves(board, &mut handler);
            }
        }
        1 => {
            Enumerate_Moves!(true, board, diagonal_pins, linear_pins, handler);
        }
        _ => {}
    }
    enumerate_king_moves::<M, F>(
        board,
        board.allied_king().to_square().unwrap(),
        &mut handler,
    );
    true
}

/// Enumerates the normal pawn moves for the given board, considering quiet moves and tactical moves.
///  
/// This function handles the generation of all possible pawn normal moves, including:
/// - Single and double pushes, with special handling for pawns on the second or seventh ranks.
/// - Normal captures, considering any pins and the presence of enemy pieces.
#[inline(always)]
fn enumerate_pawn_normal_moves<const IN_CHECK: bool, M, F>(
    board: &Board,
    src: BitBoard,
    diagonal_pins: BitBoard,
    linear_pins: BitBoard,
    handler: &mut F,
) -> bool
where
    M: MoveFilter,
    F: FnMut(Move) -> bool,
{
    const RANK_7: [BitBoard; 2] = [BitBoard::RANK_7, BitBoard::RANK_2];
    const RANK_3: [BitBoard; 2] = [BitBoard::RANK_3, BitBoard::RANK_6];

    //Single & Double Push
    if M::QUIETS {
        let pawns: BitBoard = src & !RANK_7[board.side as usize] & !diagonal_pins;

        // Non-promotion single pawn pushes.
        let mut single_push: BitBoard = ((pawns & !linear_pins).forward(board.side)
            | ((pawns & linear_pins).forward(board.side) & linear_pins))
            & !board.combined_bitboard();

        let mut double_push: BitBoard = (single_push & RANK_3[board.side as usize])
            .forward(board.side)
            & !board.combined_bitboard();

        if IN_CHECK {
            single_push &= check_mask::<IN_CHECK>(board);
            double_push &= check_mask::<IN_CHECK>(board);
        }

        for dest in single_push {
            let src: Square = dest.backward(board.side);
            Call_Handler!(handler, src, dest, Quiet);
        }

        for dest in double_push {
            let src: Square = (dest.backward(board.side)).backward(board.side);
            Call_Handler!(handler, src, dest, DoublePawn);
        }
    }

    // Normal Captures (Non promotions)
    if M::TACTICALS {
        let pawns: BitBoard = src & !RANK_7[board.side as usize] & !linear_pins;
        let mut capture_left: BitBoard = ((pawns & !diagonal_pins).up_left(board.side)
            | ((pawns & diagonal_pins).up_left(board.side) & diagonal_pins))
            & board.enemy_presence();
        let mut capture_right: BitBoard = ((pawns & !diagonal_pins).up_right(board.side)
            | ((pawns & diagonal_pins).up_right(board.side) & diagonal_pins))
            & board.enemy_presence();

        if IN_CHECK {
            capture_left &= check_mask::<IN_CHECK>(board);
            capture_right &= check_mask::<IN_CHECK>(board);
        }

        for dest in capture_left {
            let src: Square = dest.backward(board.side).right_color(board.side);
            Call_Handler!(handler, src, dest, Capture);
        }

        for dest in capture_right {
            let src: Square = dest.backward(board.side).left_color(board.side);
            Call_Handler!(handler, src, dest, Capture);
        }
    }

    true
}

/// Enumerates all pawn promotion moves for the given board, considering both quiet promotions
/// and capture promotions.
///
/// It handles both:
/// - Capture promotions, where pawns capture an enemy piece diagonally and promote.
/// - Quiet promotions, where pawns advance forward and promote without capturing.
#[inline(always)]
fn enumerate_pawn_promotion_moves<const IN_CHECK: bool, M, F>(
    board: &Board,
    src: BitBoard,
    diagonal_pins: BitBoard,
    linear_pins: BitBoard,
    handler: &mut F,
) -> bool
where
    M: MoveFilter,
    F: FnMut(Move) -> bool,
{
    const RANK_7: [BitBoard; 2] = [BitBoard::RANK_7, BitBoard::RANK_2];

    let pawns_to_promote: BitBoard = src & RANK_7[board.side as usize];

    if pawns_to_promote.0 != 0 {
        // Capture Promotions
        {
            let pawns: BitBoard = pawns_to_promote & !linear_pins;
            let mut capture_left_prom: BitBoard = ((pawns & !diagonal_pins).up_left(board.side)
                | ((pawns & diagonal_pins).up_left(board.side) & diagonal_pins))
                & board.enemy_presence();
            let mut capture_right_prom: BitBoard = ((pawns & !diagonal_pins).up_right(board.side)
                | ((pawns & diagonal_pins).up_right(board.side) & diagonal_pins))
                & board.enemy_presence();

            if IN_CHECK {
                capture_left_prom &= check_mask::<IN_CHECK>(board);
                capture_right_prom &= check_mask::<IN_CHECK>(board);
            }

            for dest in capture_left_prom {
                let src: Square = dest.backward(board.side).right_color(board.side);
                enumerate_promotions::<M, F>(src, dest, handler, true);
            }

            for dest in capture_right_prom {
                let src: Square = dest.backward(board.side).left_color(board.side);
                enumerate_promotions::<M, F>(src, dest, handler, true);
            }
        }

        // Quiet Promotions
        {
            let pawns: BitBoard = pawns_to_promote & !diagonal_pins;
            let mut quiet_promotions: BitBoard = ((pawns & !linear_pins).forward(board.side)
                | ((pawns & linear_pins).forward(board.side) & linear_pins))
                & !board.combined_bitboard();

            if IN_CHECK {
                quiet_promotions &= check_mask::<IN_CHECK>(board);
            }

            for dest in quiet_promotions {
                let src: Square = dest.backward(board.side);
                enumerate_promotions::<M, F>(src, dest, handler, false);
            }
        }
    }
    true
}

/// Enumerates all possible pawn promotion moves for a given pawn that has reached the promotion rank.
/// The function handles both capture and quiet promotions, allowing the pawn to promote to any of the four pieces:
/// Queen, Rook, Bishop, or Knight.
///  
/// It handles:
/// - Tactical moves (capture and quiet promotions) to Queen.
/// - Quiet moves to Rook, Bishop, or Knight.
#[inline(always)]
fn enumerate_promotions<M, F>(src: Square, dest: Square, handler: &mut F, capture: bool) -> bool
where
    M: MoveFilter,
    F: FnMut(Move) -> bool,
{
    macro_rules! Call_Promotion {
        ($promo_type:ident, $cap_type:ident) => {
            if capture {
                Call_Handler!(handler, src, dest, $cap_type);
            } else {
                Call_Handler!(handler, src, dest, $promo_type);
            }
        };
    }

    if M::TACTICALS {
        Call_Promotion!(PromotionQueen, CapPromoQueen);
    }

    if M::QUIETS {
        Call_Promotion!(PromotionRook, CapPromoRook);
        Call_Promotion!(PromotionBishop, CapPromoBishop);
        Call_Promotion!(PromotionKnight, CapPromoKnight);
    }

    true
}

/// Enumerates all possible pawn en passant moves for the given board, considering the current game state.
/// This function checks if any pawn can capture an enemy pawn using the en passant rule and ensures that
/// the move does not expose the king to any attacks.
///
/// The function works by first identifying the en passant square, then checking which pawns can attack
/// that square. It ensures that performing an en passant capture does not leave the king vulnerable to
/// attacks by rooks, queens, or bishops.
#[inline(always)]
fn enumerate_pawn_en_passant_moves<F>(
    board: &Board,
    src: BitBoard,
    linear_pins: BitBoard,
    handler: &mut F,
) -> bool
where
    F: FnMut(Move) -> bool,
{
    let pawns: BitBoard = src & !linear_pins;
    let king_square: Square = board.allied_king().to_square().unwrap();

    // En Passant captures
    if let Some(en_passant) = board.enpassant_square {
        let dest: Square = en_passant;
        let victim: Square = en_passant.forward(!board.side);

        // Check which pawns can capture en passant.
        for src in pawns & get_pawn_attacks(!board.side, dest) {
            // Simulate the board after en passant capture.
            let blockers: BitBoard =
                board.combined_bitboard() ^ victim.to_bitboard() ^ src.to_bitboard()
                    | dest.to_bitboard();

            // Ensure en passant does not expose the king to a rook or queen attack.
            let king_ray: bool =
                !(get_rook_rays(king_square) & board.enemy_queen_rooks()).is_empty();
            if king_ray
                && !(get_rook_attacks(king_square, blockers) & board.enemy_queen_rooks()).is_empty()
            {
                continue;
            }

            // Ensure en passant does not expose the king to a bishop or queen attack.
            let king_ray: bool =
                !(get_bishop_rays(king_square) & board.enemy_queen_bishops()).is_empty();
            if king_ray
                && !(get_bishop_attacks(king_square, blockers) & board.enemy_queen_bishops())
                    .is_empty()
            {
                continue;
            }

            Call_Handler!(handler, src, dest, EnPassant);
        }
    }
    true
}

/// Enumerates all possible pawn moves for the given board, including normal moves, promotions,
/// and en passant captures.
/// The function handles different types of pawn moves based on the game state and the `MoveFilter` trait.
#[inline(always)]
fn enumerate_pawn_moves<const IN_CHECK: bool, M, F>(
    board: &Board,
    src: BitBoard,
    diagonal_pins: BitBoard,
    linear_pins: BitBoard,
    handler: &mut F,
) -> bool
where
    M: MoveFilter,
    F: FnMut(Move) -> bool,
{
    enumerate_pawn_normal_moves::<IN_CHECK, M, F>(board, src, diagonal_pins, linear_pins, handler);
    enumerate_pawn_promotion_moves::<IN_CHECK, M, F>(
        board,
        src,
        diagonal_pins,
        linear_pins,
        handler,
    );
    if M::TACTICALS {
        enumerate_pawn_en_passant_moves::<F>(board, src, linear_pins, handler);
    }
    true
}

/// Enumerates all possible castling moves for the current side, both kingside and queenside castling.
/// The function checks if castling is available and whether the king and relevant squares are not under attack,
/// and if there are no obstructions between the king and the rook.
#[inline(always)]
fn enumerate_castling_moves<F>(board: &Board, handler: &mut F) -> bool
where
    F: FnMut(Move) -> bool,
{
    // King Side Castling
    if board.castling.has_kingside(board.side) {
        let side: usize = board.side as usize;
        let src: Square = SOURCE[side];
        let dest: Square = DESTINATION[KING_SIDE][side];

        if (board.combined_bitboard() & PRESENCE[KING_SIDE][side]).is_empty()
            && !board.attacked_square(MEDIUM[KING_SIDE][side], board.combined_bitboard())
            && !board.attacked_square(dest, board.combined_bitboard())
        {
            Call_Handler!(handler, src, dest, KingCastle);
        }
    }
    // Queen Side Castling
    if board.castling.has_queenside(board.side) {
        let side: usize = board.side as usize;
        let src: Square = SOURCE[side];
        let dest: Square = DESTINATION[QUEEN_SIDE][side];

        if (board.combined_bitboard() & PRESENCE[QUEEN_SIDE][side]).is_empty()
            && !board.attacked_square(MEDIUM[QUEEN_SIDE][side], board.combined_bitboard())
            && !board.attacked_square(dest, board.combined_bitboard())
        {
            Call_Handler!(handler, src, dest, QueenCastle);
        }
    }

    true
}

/// Enumerates all legal king moves, ensuring the king does not move into an attacked square.
/// The function considers both tactical (captures) and quiet moves based on the `MoveFilter` trait.
#[inline(always)]
fn enumerate_king_moves<M, F>(board: &Board, src: Square, handler: &mut F) -> bool
where
    M: MoveFilter,
    F: FnMut(Move) -> bool,
{
    // Get all possible king moves, avoiding squares occupied by allied pieces.
    let mut king: BitBoard = get_king_attacks(src) & !board.allied_presence();
    let blockers: BitBoard = board.combined_bitboard().pop_square(src);

    if !M::QUIETS {
        king &= board.enemy_presence()
    }
    if !M::TACTICALS {
        king &= !board.enemy_presence()
    }

    // Iterate through the possible king moves and ensure the king does not move into check.
    for dest in king {
        if !board.attacked_square(dest, blockers) {
            let is_capture: bool = (board.enemy_presence().0 & dest.to_bitboard().0) != 0;
            let move_type: MoveType = if is_capture {
                MoveType::Capture
            } else {
                MoveType::Quiet
            };
            handler(Move::new(src, dest, move_type));
        }
    }
    true
}

/// Enumerates all legal knight moves, considering possible checks and move type constraints.
/// This function ensures that pinned knights cannot move and filters moves based on tactical
/// or quiet move generation flags.
#[inline(always)]
fn enumerate_knight_moves<const IN_CHECK: bool, M, F>(
    board: &Board,
    src: BitBoard,
    diagonal_pins: BitBoard,
    linear_pins: BitBoard,
    handler: &mut F,
) -> bool
where
    M: MoveFilter,
    F: FnMut(Move) -> bool,
{
    // Remove pinned knights from the move generation.
    let knights: BitBoard = src & !(diagonal_pins | linear_pins);

    for src in knights {
        let mut attacks: BitBoard = get_knight_attacks(src) & !board.allied_presence();

        // If in check, restrict moves to those that block or capture the checking piece.
        if IN_CHECK {
            attacks &= check_mask::<IN_CHECK>(board);
        }

        if !M::QUIETS {
            attacks &= board.enemy_presence();
        }

        if !M::TACTICALS {
            attacks &= !board.enemy_presence();
        }

        for dest in attacks {
            let is_capture: bool = (board.enemy_presence().0 & dest.to_bitboard().0) != 0;
            let move_type: MoveType = if is_capture {
                MoveType::Capture
            } else {
                MoveType::Quiet
            };
            handler(Move::new(src, dest, move_type));
        }
    }
    true
}

/// Enumerates all legal bishop moves, considering check restrictions, pinning, and move type constraints.
///
/// - Bishops that are not pinned can move freely along diagonal lines.
/// - Pinned bishops can only move along the pinning diagonal.
/// - The function filters moves based on the requested move type (tactical or quiet).
/// - If the king is in check, moves are restricted to those that block or capture the checking piece.
///
#[inline(always)]
fn enumerate_bishop_moves<const IN_CHECK: bool, M, F>(
    board: &Board,
    src: BitBoard,
    diagonal_pins: BitBoard,
    linear_pins: BitBoard,
    handler: &mut F,
) -> bool
where
    M: MoveFilter,
    F: FnMut(Move) -> bool,
{
    // Non pinned Bishops|Queens
    let bishops: BitBoard = src & !linear_pins & !diagonal_pins;

    for src in bishops {
        let mut attacks: BitBoard =
            get_bishop_attacks(src, board.combined_bitboard()) & !board.allied_presence();

        if IN_CHECK {
            attacks &= check_mask::<IN_CHECK>(board);
        }

        if !M::QUIETS {
            attacks &= board.enemy_presence();
        }

        if !M::TACTICALS {
            attacks &= !board.enemy_presence();
        }

        for dest in attacks {
            let is_capture: bool = (board.enemy_presence().0 & dest.to_bitboard().0) != 0;
            let move_type: MoveType = if is_capture {
                MoveType::Capture
            } else {
                MoveType::Quiet
            };
            handler(Move::new(src, dest, move_type));
        }
    }

    // Pinned Bishops|Queens along diagonal lines.
    let bishops: BitBoard = src & !linear_pins & diagonal_pins;

    for src in bishops {
        let mut attacks: BitBoard = get_bishop_attacks(src, board.combined_bitboard())
            & !board.allied_presence()
            & diagonal_pins;

        if IN_CHECK {
            attacks &= check_mask::<IN_CHECK>(board);
        }

        if !M::QUIETS {
            attacks &= board.enemy_presence();
        }

        if !M::TACTICALS {
            attacks &= !board.enemy_presence();
        }

        for dest in attacks {
            let is_capture: bool = (board.enemy_presence().0 & dest.to_bitboard().0) != 0;
            let move_type: MoveType = if is_capture {
                MoveType::Capture
            } else {
                MoveType::Quiet
            };
            handler(Move::new(src, dest, move_type));
        }
    }
    true
}

/// Enumerates all legal rook moves, considering check restrictions, pinning, and move type constraints.
///
/// - Rooks that are not pinned can move freely along rank and file.
/// - Pinned rooks can only move along the pinning file or rank.
/// - The function filters moves based on the requested move type (tactical or quiet).
/// - If the king is in check, moves are restricted to those that block or capture the checking piece.
#[inline(always)]
fn enumerate_rook_moves<const IN_CHECK: bool, M, F>(
    board: &Board,
    src: BitBoard,
    diagonal_pins: BitBoard,
    linear_pins: BitBoard,
    handler: &mut F,
) -> bool
where
    M: MoveFilter,
    F: FnMut(Move) -> bool,
{
    // Non pinned Rooks|Queens
    let rooks: BitBoard = src & !diagonal_pins & !linear_pins;

    for src in rooks {
        let mut attacks: BitBoard =
            get_rook_attacks(src, board.combined_bitboard()) & !board.allied_presence();

        if IN_CHECK {
            attacks &= check_mask::<IN_CHECK>(board);
        }

        if !M::QUIETS {
            attacks &= board.enemy_presence();
        }

        if !M::TACTICALS {
            attacks &= !board.enemy_presence();
        }

        for dest in attacks {
            let is_capture: bool = (board.enemy_presence().0 & dest.to_bitboard().0) != 0;
            let move_type: MoveType = if is_capture {
                MoveType::Capture
            } else {
                MoveType::Quiet
            };
            handler(Move::new(src, dest, move_type));
        }
    }

    // Pinned Rooks|Queens along rank or file.
    let rooks: BitBoard = src & !diagonal_pins & linear_pins;

    for src in rooks {
        let mut attacks: BitBoard = get_rook_attacks(src, board.combined_bitboard())
            & !board.allied_presence()
            & linear_pins;

        if IN_CHECK {
            attacks &= check_mask::<IN_CHECK>(board);
        }

        if !M::QUIETS {
            attacks &= board.enemy_presence();
        }

        if !M::TACTICALS {
            attacks &= !board.enemy_presence();
        }

        for dest in attacks {
            let is_capture: bool = (board.enemy_presence().0 & dest.to_bitboard().0) != 0;
            let move_type: MoveType = if is_capture {
                MoveType::Capture
            } else {
                MoveType::Quiet
            };
            handler(Move::new(src, dest, move_type));
        }
    }
    true
}

/// Identifies all possible squares where a piece could be pinned to the king.
///
/// This function determines squares that are along a potential pinning line
/// between the king and an enemy sliding piece (bishop, rook, or queen). It does **not**
/// return the pinned pieces directly, but rather the bitboard of squares where a piece
/// could be pinned.
///
/// **How it works**:
/// 1. Determines which squares could potentially contain pinned pieces.
/// 2. Simulates removing those pieces to check if an enemy piece is attacking the king.
/// 3. Collects all such pinning paths and returns them as bitboards.
#[inline(always)]
fn pinners(board: &Board) -> (BitBoard, BitBoard) {
    let king_square: Square = board.allied_king().to_square().unwrap();
    let blockers_mask: BitBoard = board.combined_bitboard();

    let probe: BitBoard = (get_bishop_rays(king_square) | get_rook_rays(king_square))
        & (board.enemy_queen_bishops() | board.enemy_queen_rooks());

    if probe.is_empty() {
        return (BitBoard::EMPTY, BitBoard::EMPTY);
    }

    // Identify squares along potential pinning paths (diagonal and linear).
    let diagonal_pinned: BitBoard =
        get_bishop_attacks(king_square, blockers_mask) & board.allied_presence();
    let linnear_pinned: BitBoard =
        get_rook_attacks(king_square, blockers_mask) & board.allied_presence();

    // Simulate removing those pieces to check if the king would be attacked.
    let diagonal_pinned_removed: BitBoard = blockers_mask & !diagonal_pinned;
    let linear_pinned_removed: BitBoard = blockers_mask & !linnear_pinned;

    // Find enemy attackers that could be pinning a piece along diagonal or linear paths.
    let diagonal_attackers: BitBoard =
        get_bishop_attacks(king_square, diagonal_pinned_removed) & board.enemy_queen_bishops();
    let linear_attackers: BitBoard =
        get_rook_attacks(king_square, linear_pinned_removed) & board.enemy_queen_rooks();

    // Get squares along the diagonal pinning line.
    let mut diagonal_pins: BitBoard = BitBoard::EMPTY;
    for attacker in diagonal_attackers {
        let pin: BitBoard = get_between(king_square, attacker);
        diagonal_pins |= pin;
    }

    // Get squares along the linear (orthogonal) pinning line.
    let mut linear_pins: BitBoard = BitBoard::EMPTY;
    for attacker in linear_attackers {
        let pin: BitBoard = get_between(king_square, attacker);
        linear_pins |= pin;
    }

    (diagonal_pins, linear_pins)
}

/// Generates a bitboard mask that restricts legal moves when the king is in check.
///
/// - If the king is in check, the mask includes only the squares between the king and the attacking piece,
///   as well as the square occupied by the checker. This ensures only blocking or capturing moves are considered.
/// - If the king is not in check, the mask allows movement to any square.
#[inline(always)]
fn check_mask<const IN_CHECK: bool>(board: &Board) -> BitBoard {
    if IN_CHECK {
        get_between(
            board.allied_king().to_square().unwrap(),
            board.checkers.to_square().unwrap(),
        ) | board.checkers
    } else {
        BitBoard::FULL
    }
}