From 82aa0628485445dac583c9b5a8a3e93f2adb5050 Mon Sep 17 00:00:00 2001 From: nook0110 Date: Sun, 8 Nov 2026 23:40:26 +0300 Subject: [PATCH] [core] Track move legality in the type system Moves now carry their legality in their type. PseudoLegalMove and LegalMove wrap Move with no size or speed cost; MaybeLegalMove is the two-byte "legal move or none" the move picker returns. Only the move generator, the picker's checked return paths and the checked conversions Position::TryPseudoLegal and Position::TryLegal can create them, and Position::DoMove/UndoMove accept only LegalMove, so search, quiescence, perft, PV and ponder code cannot play an unchecked move. UCI "position ... moves" now validates every move and stops at the first illegal one with "info string illegal move "; before, an illegal move was played into a corrupted position. Syzygy root moves are validated the same way. Search is node-for-node identical on 30 positions at depth 11, and instructions per node are unchanged (11977-11985 vs 11976-11982). Co-Authored-By: Claude Opus 5.5 --- Chess/MoveGenerator.cpp | 78 +++++++++++-------- Chess/MoveGenerator.h | 17 +++-- Chess/MovePicker.cpp | 22 +++--- Chess/MovePicker.h | 4 +- Chess/Perft.cpp | 2 +- Chess/Position.cpp | 8 +- Chess/Position.h | 38 +++++++++- Chess/Quiescence.cpp | 14 ++-- Chess/SearchImplementation.h | 15 ++-- Chess/Searcher.h | 9 ++- Chess/SimpleChessEngine.h | 8 +- Chess/SyzygyTablebase.cpp | 8 +- Chess/SyzygyTablebase.h | 4 +- Chess/TypedMove.h | 124 +++++++++++++++++++++++++++++++ Chess/UciCommunicator.h | 33 +++++++- Tests/CheckedMove.h | 19 +++++ Tests/ChessEngineTests.cpp | 7 +- Tests/MoveGeneratorTests.cpp | 2 +- Tests/NnueTests.cpp | 4 +- Tests/PositionTests.cpp | 41 +++++----- Tests/SearchCorrectnessTests.cpp | 7 +- Tests/StagedMovePickerTests.cpp | 31 ++++---- Tests/TypedMoveTests.cpp | 107 ++++++++++++++++++++++++++ 23 files changed, 472 insertions(+), 130 deletions(-) create mode 100644 Chess/TypedMove.h create mode 100644 Tests/CheckedMove.h create mode 100644 Tests/TypedMoveTests.cpp diff --git a/Chess/MoveGenerator.cpp b/Chess/MoveGenerator.cpp index e996b9c..060012e 100644 --- a/Chess/MoveGenerator.cpp +++ b/Chess/MoveGenerator.cpp @@ -16,7 +16,8 @@ template MoveGenerator::Moves MoveGenerator::GenerateMoves< MoveGenerator::~MoveGenerator() = default; -void MoveGenerator::GenerateCastling(Move*& moves, const Position& position) { +void MoveGenerator::GenerateCastling(PseudoLegalMove*& moves, + const Position& position) { if (position.IsUnderCheck()) { return; } @@ -30,13 +31,14 @@ void MoveGenerator::GenerateCastling(Move*& moves, const Position& position) { const auto side_idx = static_cast(castling_side); const auto king_to = kKingCastlingDestination[color_idx][side_idx]; - *moves++ = Move::Make(king_square, king_to); + *moves++ = PseudoLegalMove( + Move::Make(king_square, king_to)); } } } template -void MoveGenerator::GenerateMovesForPiece(Move*& moves, Position& position, +void MoveGenerator::GenerateMovesForPiece(PseudoLegalMove*& moves, Position& position, const Bitboard target) const { static_assert(piece != Piece::kPawn && piece != Piece::kKing); @@ -51,7 +53,7 @@ void MoveGenerator::GenerateMovesForPiece(Move*& moves, Position& position, template <> void MoveGenerator::GenerateMovesForPiece( - Move*& moves, Position& position, const Bitboard target) const { + PseudoLegalMove*& moves, Position& position, const Bitboard target) const { const auto us = position.GetSideToMove(); const auto us_idx = static_cast(us); const auto them = Flip(us); @@ -76,7 +78,7 @@ void MoveGenerator::GenerateMovesForPiece( while (push.Any()) { const auto to = push.PopFirstBit(); const auto from = Shift(to, opposite_direction); - *moves++ = Move(from, to); + *moves++ = PseudoLegalMove(Move(from, to)); } auto double_push = Shift(double_push_pawns, direction) & valid_squares; @@ -85,7 +87,7 @@ void MoveGenerator::GenerateMovesForPiece( while (double_push.Any()) { const auto to = double_push.PopFirstBit(); const auto from = Shift(Shift(to, opposite_direction), opposite_direction); - *moves++ = Move(from, to); + *moves++ = PseudoLegalMove(Move(from, to)); } static constexpr std::array cant_attack_files = {kFileBB[0], kFileBB[7]}; @@ -115,7 +117,7 @@ void MoveGenerator::GenerateMovesForPiece( while (attack_squares.Any()) { const auto to = attack_squares.PopFirstBit(); const auto from = Shift(to, opposite_attacks[attack_direction]); - *moves++ = Move(from, to); + *moves++ = PseudoLegalMove(Move(from, to)); } } @@ -128,7 +130,7 @@ void MoveGenerator::GenerateMovesForPiece( if (attack_to.Any()) { const auto to = en_croissant_square.value(); const auto from = Shift(to, opposite_attacks[attack_direction]); - *moves++ = Move::Make(from, to); + *moves++ = PseudoLegalMove(Move::Make(from, to)); } } } @@ -142,10 +144,14 @@ void MoveGenerator::GenerateMovesForPiece( const auto to = promotion_push.PopFirstBit(); const auto from = Shift(to, opposite_direction); - *moves++ = Move::Make(from, to, Piece::kQueen); - *moves++ = Move::Make(from, to, Piece::kKnight); - *moves++ = Move::Make(from, to, Piece::kRook); - *moves++ = Move::Make(from, to, Piece::kBishop); + *moves++ = PseudoLegalMove( + Move::Make(from, to, Piece::kQueen)); + *moves++ = PseudoLegalMove( + Move::Make(from, to, Piece::kKnight)); + *moves++ = PseudoLegalMove( + Move::Make(from, to, Piece::kRook)); + *moves++ = PseudoLegalMove( + Move::Make(from, to, Piece::kBishop)); } for (size_t attack_direction = 0; attack_direction < attacks.size(); @@ -159,17 +165,21 @@ void MoveGenerator::GenerateMovesForPiece( const auto to = attack_squares.PopFirstBit(); const auto from = Shift(to, opposite_attacks[attack_direction]); - *moves++ = Move::Make(from, to, Piece::kQueen); - *moves++ = Move::Make(from, to, Piece::kKnight); - *moves++ = Move::Make(from, to, Piece::kRook); - *moves++ = Move::Make(from, to, Piece::kBishop); + *moves++ = PseudoLegalMove( + Move::Make(from, to, Piece::kQueen)); + *moves++ = PseudoLegalMove( + Move::Make(from, to, Piece::kKnight)); + *moves++ = PseudoLegalMove( + Move::Make(from, to, Piece::kRook)); + *moves++ = PseudoLegalMove( + Move::Make(from, to, Piece::kBishop)); } } } template -Move* MoveGenerator::GeneratePseudoLegal(Position& position, - Move* moves) const { +PseudoLegalMove* MoveGenerator::GeneratePseudoLegal(Position& position, + PseudoLegalMove* moves) const { const auto us = position.GetSideToMove(); const auto them = Flip(us); auto target = ~position.GetPieces(us); @@ -239,37 +249,39 @@ Move* MoveGenerator::GeneratePseudoLegal(Position& position, template MoveGenerator::Moves MoveGenerator::GenerateMoves(Position& position) const { - std::array moves; + std::array moves; auto* end = GeneratePseudoLegal(position, moves.data()); position.ComputePins(position.GetSideToMove()); Moves legal; legal.reserve(end - moves.data()); for (auto* p = moves.data(); p != end; ++p) { - if (position.IsLegal(*p)) legal.push_back(*p); + if (position.IsLegal(*p)) legal.push_back(LegalMove(static_cast(*p))); } return legal; } bool MoveGenerator::HasLegalMove(Position& position) const { - std::array moves; + std::array moves; auto* end = GeneratePseudoLegal(position, moves.data()); position.ComputePins(position.GetSideToMove()); return std::any_of(moves.data(), end, - [&position](Move move) { return position.IsLegal(move); }); + [&position](Move move) { + return position.IsLegal(move); + }); } -template Move* MoveGenerator::GeneratePseudoLegal( - Position&, Move*) const; -template Move* +template PseudoLegalMove* MoveGenerator::GeneratePseudoLegal( + Position&, PseudoLegalMove*) const; +template PseudoLegalMove* MoveGenerator::GeneratePseudoLegal(Position&, - Move*) const; -template Move* MoveGenerator::GeneratePseudoLegal( - Position&, Move*) const; -template Move* MoveGenerator::GeneratePseudoLegal< - MoveGenerator::Type::kQuiescence>(Position&, Move*) const; + PseudoLegalMove*) const; +template PseudoLegalMove* MoveGenerator::GeneratePseudoLegal( + Position&, PseudoLegalMove*) const; +template PseudoLegalMove* MoveGenerator::GeneratePseudoLegal< + MoveGenerator::Type::kQuiescence>(Position&, PseudoLegalMove*) const; template <> -void MoveGenerator::GenerateMovesForPiece(Move*& moves, +void MoveGenerator::GenerateMovesForPiece(PseudoLegalMove*& moves, Position& position, Bitboard target) const { GenerateMovesFromSquare( @@ -278,7 +290,7 @@ void MoveGenerator::GenerateMovesForPiece(Move*& moves, } template -void MoveGenerator::GenerateMovesFromSquare(Move*& moves, Position& position, +void MoveGenerator::GenerateMovesFromSquare(PseudoLegalMove*& moves, Position& position, const BitIndex from, Bitboard target) const { assert(position.GetPieceAt(from) == piece); @@ -292,7 +304,7 @@ void MoveGenerator::GenerateMovesFromSquare(Move*& moves, Position& position, while (valid_moves.Any()) { const auto to = valid_moves.PopFirstBit(); - *moves++ = Move(from, to); + *moves++ = PseudoLegalMove(Move(from, to)); } } } // namespace SimpleChessEngine diff --git a/Chess/MoveGenerator.h b/Chess/MoveGenerator.h index bbc6798..cb8fb2c 100644 --- a/Chess/MoveGenerator.h +++ b/Chess/MoveGenerator.h @@ -26,7 +26,7 @@ class MoveGenerator { MoveGenerator() = default; ~MoveGenerator(); - using Moves = std::vector; + using Moves = std::vector; /** * \brief Generates all possible moves for a given position. @@ -39,8 +39,13 @@ class MoveGenerator { [[nodiscard]] Moves GenerateMoves(Position& position) const; template - [[nodiscard]] Move* GeneratePseudoLegal(Position& position, - Move* moves) const; + [[nodiscard, gnu::always_inline]] Moves GenerateLegalMoves(Position& position) const { + return GenerateMoves(position); + } + + template + [[nodiscard]] PseudoLegalMove* GeneratePseudoLegal(Position& position, + PseudoLegalMove* moves) const; [[nodiscard]] bool HasLegalMove(Position& position) const; @@ -55,7 +60,7 @@ class MoveGenerator { * \return All possible moves for the given square. */ template - void GenerateMovesForPiece(Move*& moves, Position& position, + void GenerateMovesForPiece(PseudoLegalMove*& moves, Position& position, Bitboard target) const; /** @@ -70,10 +75,10 @@ class MoveGenerator { * \return All possible moves for the given square and piece. */ template - void GenerateMovesFromSquare(Move*& moves, Position& position, BitIndex from, + void GenerateMovesFromSquare(PseudoLegalMove*& moves, Position& position, BitIndex from, Bitboard target) const; - static void GenerateCastling(Move*& moves, const Position& position); + static void GenerateCastling(PseudoLegalMove*& moves, const Position& position); }; } // namespace SimpleChessEngine diff --git a/Chess/MovePicker.cpp b/Chess/MovePicker.cpp index 604ed72..54eca22 100644 --- a/Chess/MovePicker.cpp +++ b/Chess/MovePicker.cpp @@ -61,9 +61,9 @@ void MovePicker::InitPicker(Position& position, const Searcher* searcher, } void MovePicker::Generate(bool quiet) { - std::array generated; + std::array generated; auto* begin = generated.data(); - Move* end; + PseudoLegalMove* end; const MoveGenerator generator; if (quiet) { end = generator.GeneratePseudoLegal( @@ -108,18 +108,18 @@ void MovePicker::Generate(bool quiet) { } } -Move MovePicker::Emit(Move move) { +LegalMove MovePicker::Emit(LegalMove move) { ++move_count_; return move; } -Move MovePicker::SelectNextMove() { +MaybeLegalMove MovePicker::SelectNextMove() { for (;;) { switch (stage_) { case Stage::kTT: stage_ = Stage::kCaptureInit; if (tt_move_.IsValid() && position_->IsLegal(tt_move_, blockers_)) - return Emit(tt_move_); + return Emit(Position::AssumeLegal(tt_move_)); break; case Stage::kCaptureInit: Generate(false); @@ -129,14 +129,14 @@ Move MovePicker::SelectNextMove() { while (current_ < end_) { const auto candidate = moves_[current_++]; if (!position_->IsLegal(candidate.move, blockers_)) continue; - if (!searcher_) return Emit(candidate.move); + if (!searcher_) return Emit(Position::AssumeLegal(candidate.move)); const auto promotion = candidate.move.IsPromotion() ? candidate.move.PromotionPiece() : Piece::kNone; if (!IsUnderpromotion(promotion) && position_->StaticExchangeEvaluation(candidate.move, kGoodCaptureThreshold)) - return Emit(candidate.move); + return Emit(Position::AssumeLegal(candidate.move)); moves_[bad_end_++] = candidate; } stage_ = searcher_ ? Stage::kKillers : Stage::kEnd; @@ -158,7 +158,7 @@ Move MovePicker::SelectNextMove() { found->move = Move::None(); } killers_[index] = move; - return Emit(move); + return Emit(Position::AssumeLegal(move)); } stage_ = Stage::kQuietInit; break; @@ -170,7 +170,7 @@ Move MovePicker::SelectNextMove() { case Stage::kQuiet: while (current_ < end_) { const auto move = moves_[current_++].move; - if (position_->IsLegal(move, blockers_)) return Emit(move); + if (position_->IsLegal(move, blockers_)) return Emit(Position::AssumeLegal(move)); } current_ = 0; end_ = bad_end_; @@ -179,12 +179,12 @@ Move MovePicker::SelectNextMove() { case Stage::kBadCaptures: while (current_ < end_) { const auto move = moves_[current_++].move; - if (move.IsValid()) return Emit(move); + if (move.IsValid()) return Emit(Position::AssumeLegal(move)); } stage_ = Stage::kEnd; break; case Stage::kEnd: - return Move::None(); + return MaybeLegalMove::None(); } } } diff --git a/Chess/MovePicker.h b/Chess/MovePicker.h index e72726d..f2d18db 100644 --- a/Chess/MovePicker.h +++ b/Chess/MovePicker.h @@ -27,7 +27,7 @@ class MovePicker { void InitPicker(Position& position, const Searcher* searcher, Depth ply, Move tt_move = Move::None(), Move excluded_move = Move::None()); - [[nodiscard]] Move SelectNextMove(); + [[nodiscard]] MaybeLegalMove SelectNextMove(); [[nodiscard]] Stage GetCurrentStage() const { return stage_; } [[nodiscard]] std::ptrdiff_t MoveCount() const { return move_count_; } @@ -41,7 +41,7 @@ class MovePicker { static void PartialInsertionSort(ScoredMove* begin, ScoredMove* end, std::int64_t limit); void Generate(bool quiet); - [[nodiscard]] Move Emit(Move move); + [[nodiscard]] LegalMove Emit(LegalMove move); std::array moves_; std::array killers_{}; diff --git a/Chess/Perft.cpp b/Chess/Perft.cpp index 5c95aa5..60de08a 100644 --- a/Chess/Perft.cpp +++ b/Chess/Perft.cpp @@ -13,7 +13,7 @@ size_t Perft(std::ostream& o_stream, Position& position, const Depth depth) { static auto move_generator = MoveGenerator{}; const auto moves = - move_generator.GenerateMoves(position); + move_generator.GenerateLegalMoves(position); size_t answer{}; diff --git a/Chess/Position.cpp b/Chess/Position.cpp index c7692b3..52f209e 100644 --- a/Chess/Position.cpp +++ b/Chess/Position.cpp @@ -93,7 +93,7 @@ void Position::MovePiece(const BitIndex from, const BitIndex to, hash_ ^= hasher_.psqt_hash[piece_idx][color_idx][to]; } -void Position::DoMove(const Move &move) { +void Position::DoMove(const LegalMove &move) { if (const auto &ep_square = irreversible_data_.en_croissant_square; ep_square.has_value()) { hash_ ^= hasher_.en_croissant_hash[GetCoordinates(ep_square.value()).first]; @@ -239,7 +239,7 @@ void SimpleChessEngine::Position::DoMove(NullMove) { } -void Position::UndoMove(const Move &move, const IrreversibleData &data) { +void Position::UndoMove(const LegalMove &move, const IrreversibleData &data) { const auto &ep_square = irreversible_data_.en_croissant_square; for (const auto color : {Player::kWhite, Player::kBlack}) { hash_ ^= hasher_.cr_hash[static_cast( @@ -345,11 +345,11 @@ bool Position::IsPseudoLegal(const Move &move) { const auto to = move.To(); if (!GetPieces(side_to_move_).Test(from)) return false; if (!move.IsNormal()) { - std::array moves; + std::array moves; const auto *end = MoveGenerator{}.GeneratePseudoLegal( *this, moves.data()); - return std::find(static_cast(moves.data()), end, move) != end; + return std::find(static_cast(moves.data()), end, move) != end; } if ((move.Raw() & 0x3000) || from == to || GetPieces(side_to_move_).Test(to)) return false; diff --git a/Chess/Position.h b/Chess/Position.h index 3eb8463..6424fb0 100644 --- a/Chess/Position.h +++ b/Chess/Position.h @@ -3,11 +3,14 @@ #include #include #include +#include #include "BitBoard.h" #include "Evaluation.h" +#include "Concepts.h" +#include "NodeType.h" #include "Hasher.h" -#include "Move.h" +#include "TypedMove.h" #include "Nnue/Accumulator.h" #include "Nnue/Nnue.h" #include "Piece.h" @@ -15,6 +18,15 @@ #include "Utility.h" namespace SimpleChessEngine { +class Position; +template +size_t Perft(std::ostream&, Position&, Depth); +template + requires StopSearchCondition +struct SearchNode; +template + requires StopSearchCondition +class Quiescence; namespace Tablebase { class PositionBuilder; } @@ -128,18 +140,35 @@ class Position { * * \param move Move to do. */ - void DoMove(const Move &move); + void DoMove(const LegalMove &move); /** * \brief Undoes given move. * * \param move Move to undo. */ - void UndoMove(const Move &move, const IrreversibleData &data); + void UndoMove(const LegalMove &move, const IrreversibleData &data); void DoMove(NullMove); void UndoMove(NullMove, const IrreversibleData &data); + [[nodiscard, gnu::always_inline]] MaybePseudoLegalMove TryPseudoLegal(const Move& move) { + return IsPseudoLegal(move) ? MaybePseudoLegalMove(PseudoLegalMove(move)) + : MaybePseudoLegalMove::None(); + } + + [[nodiscard, gnu::always_inline]] std::optional TryLegal(const PseudoLegalMove& move) { + ComputePins(GetSideToMove()); + if (!IsLegal(move)) return std::nullopt; + return LegalMove(move); + } + + [[nodiscard, gnu::always_inline]] std::optional TryLegal( + const PseudoLegalMove& move, Bitboard blockers) const { + if (!IsLegal(move, blockers)) return std::nullopt; + return LegalMove(move); + } + [[nodiscard]] bool CanPseudoCastle(CastlingSide side) const; [[nodiscard]] bool IsPseudoLegal(const Move &move); [[nodiscard]] bool IsLegal(const Move &move) const; @@ -291,6 +320,9 @@ class Position { } private: + friend class MovePicker; + static constexpr LegalMove AssumeLegal(Move move) { return LegalMove(move); } + /** * \brief Places a piece with a color on a chosen square. * diff --git a/Chess/Quiescence.cpp b/Chess/Quiescence.cpp index f079768..11d3baf 100644 --- a/Chess/Quiescence.cpp +++ b/Chess/Quiescence.cpp @@ -68,8 +68,8 @@ SearchResult Quiescence::Search(Position& current_position, MovePicker picker; picker.InitPicker(current_position, nullptr, current_depth); - auto move = picker.SelectNextMove(); - if (!move.IsValid() && !move_generator_.HasLegalMove(current_position)) { + auto next = picker.SelectNextMove(); + if (!next.IsValid() && !move_generator_.HasLegalMove(current_position)) { return kDrawValue; } @@ -83,7 +83,8 @@ SearchResult Quiescence::Search(Position& current_position, alpha = stand_pat; } - for (; move.IsValid(); move = picker.SelectNextMove()) { + for (; next.IsValid(); next = picker.SelectNextMove()) { + const auto& move = *next; if (!current_position.StaticExchangeEvaluation( move, std::max(1, alpha - stand_pat - kSEEMargin))) { continue; @@ -122,13 +123,14 @@ SearchResult Quiescence::SearchUnderCheck( const Depth current_depth) { MovePicker picker; picker.InitPicker(current_position, nullptr, current_depth); - auto move = picker.SelectNextMove(); - if (!move.IsValid()) { + auto next = picker.SelectNextMove(); + if (!next.IsValid()) { return kMateValue + static_cast(std::min(current_depth, kMaxSearchPly)); } - for (; move.IsValid(); move = picker.SelectNextMove()) { + for (; next.IsValid(); next = picker.SelectNextMove()) { + const auto& move = *next; const auto irreversible_data = current_position.GetIrreversibleData(); // make the move and search the tree diff --git a/Chess/SearchImplementation.h b/Chess/SearchImplementation.h index c9893cb..f3d77a0 100644 --- a/Chess/SearchImplementation.h +++ b/Chess/SearchImplementation.h @@ -95,9 +95,9 @@ struct SearchNode { Position &GetCurrentPosition(); template - SearchResult ProbeMove(const Move &move); + SearchResult ProbeMove(const LegalMove &move); template - std::optional CheckFirstMove(const Move &move); + std::optional CheckFirstMove(const LegalMove &move); [[nodiscard]] bool CanRFP() const; [[nodiscard]] bool CanLateMovePrune() const; @@ -314,7 +314,7 @@ SearchResult SearchNode::operator()() { if (excluded_move_) return alpha; return GetEndGameScore(); } - auto has_cutoff_opt = CheckFirstMove(first_move); + auto has_cutoff_opt = CheckFirstMove(*first_move); if (!has_cutoff_opt) return std::nullopt; if (*has_cutoff_opt) { if (iteration_status_.tt_info && @@ -404,7 +404,7 @@ void SearchNode::SetTTEntry(const Bound bound) { template requires StopSearchCondition template -SearchResult SearchNode::ProbeMove(const Move &move) { +SearchResult SearchNode::ProbeMove(const LegalMove &move) { auto ¤t_position = GetCurrentPosition(); auto &[max_depth, remaining_depth, alpha, beta, ply, _] = state_; @@ -443,7 +443,7 @@ template requires StopSearchCondition template std::optional SearchNode::CheckFirstMove( - const Move &move) { + const LegalMove &move) { static_assert(expected_node_type == kFirstChildNodeExpectedType); static_assert(expected_node_type != NodeType::kPV || expected_node_type == node_type); @@ -488,8 +488,9 @@ SearchResult SearchNode::PVSearch() { const bool move_pruning_allowed = ply != 0 && !position_info_.is_under_check; - for (auto move = move_picker_.SelectNextMove(); move.IsValid(); - move = move_picker_.SelectNextMove()) { + for (auto next = move_picker_.SelectNextMove(); next; + next = move_picker_.SelectNextMove()) { + const auto& move = *next; const bool is_quiet = move.IsQuiet(current_position); const auto quiet_score = is_quiet ? searcher_.GetQuietScore(move, ply) : std::int64_t{0}; diff --git a/Chess/Searcher.h b/Chess/Searcher.h index 0efaac9..b8abeef 100644 --- a/Chess/Searcher.h +++ b/Chess/Searcher.h @@ -188,11 +188,12 @@ inline MoveGenerator::Moves Searcher::GetPrincipalVariation(Depth max_depth, hashed_node.true_hash != position.GetHash()) break; const auto legal_moves = - MoveGenerator{}.GenerateMoves(position); - if (std::ranges::find(legal_moves, hashed_node.move) == legal_moves.end()) + MoveGenerator{}.GenerateLegalMoves(position); + const auto found = std::ranges::find(legal_moves, hashed_node.move); + if (found == legal_moves.end()) break; - position.DoMove(hashed_node.move); - answer.push_back(hashed_node.move); + position.DoMove(*found); + answer.push_back(*found); } return answer; } diff --git a/Chess/SimpleChessEngine.h b/Chess/SimpleChessEngine.h index cd555ca..3032096 100644 --- a/Chess/SimpleChessEngine.h +++ b/Chess/SimpleChessEngine.h @@ -378,11 +378,11 @@ inline void SimpleChessEngine::ChessEngine::ComputeBestMove( ponder_move_.reset(); Position ponder_position = position_; const auto legal_root_moves = - MoveGenerator{}.GenerateMoves( + MoveGenerator{}.GenerateLegalMoves( ponder_position); - if (std::ranges::find(legal_root_moves, best_move_) != - legal_root_moves.end()) { - ponder_position.DoMove(best_move_); + if (const auto found = std::ranges::find(legal_root_moves, best_move_); + found != legal_root_moves.end()) { + ponder_position.DoMove(*found); if (auto ponder_pv = searcher_.GetPrincipalVariation(1, std::move(ponder_position)); !ponder_pv.empty()) { diff --git a/Chess/SyzygyTablebase.cpp b/Chess/SyzygyTablebase.cpp index b69aafc..40511d2 100644 --- a/Chess/SyzygyTablebase.cpp +++ b/Chess/SyzygyTablebase.cpp @@ -164,11 +164,15 @@ std::optional Syzygy::ProbeWdl(const Position& position) const { return result == TB_RESULT_FAILED ? std::nullopt : DecodeWdl(result); } -std::optional Syzygy::RootMove(const Position& position) const { +std::optional Syzygy::RootMove(const Position& position) const { if (!CanProbe(position)) return std::nullopt; const auto encoded = Encode(position); std::lock_guard lock(root_probe_mutex_); - return DecodeMove(ProbeRoot(encoded)); + const auto move = DecodeMove(ProbeRoot(encoded)); + if (!move) return std::nullopt; + auto validation = position; + const auto pseudo = validation.TryPseudoLegal(*move); + return pseudo ? validation.TryLegal(*pseudo) : std::nullopt; } } // namespace SimpleChessEngine::Tablebase diff --git a/Chess/SyzygyTablebase.h b/Chess/SyzygyTablebase.h index 6ee2721..46296a5 100644 --- a/Chess/SyzygyTablebase.h +++ b/Chess/SyzygyTablebase.h @@ -6,7 +6,7 @@ #include #include -#include "Move.h" +#include "TypedMove.h" #include "Tablebase.h" namespace SimpleChessEngine { @@ -23,7 +23,7 @@ class Syzygy { [[nodiscard]] std::optional Probe( const Position& position) const; [[nodiscard]] std::optional ProbeWdl(const Position& position) const; - [[nodiscard]] std::optional RootMove(const Position& position) const; + [[nodiscard]] std::optional RootMove(const Position& position) const; [[nodiscard]] std::size_t MaxPieces() const { return max_pieces_; } private: diff --git a/Chess/TypedMove.h b/Chess/TypedMove.h new file mode 100644 index 0000000..7a51409 --- /dev/null +++ b/Chess/TypedMove.h @@ -0,0 +1,124 @@ +#pragma once + +#include +#include +#include + +#include "Move.h" + +namespace SimpleChessEngine { + +class Position; +class MoveGenerator; +template class MaybeMove; +struct PseudoLegalTag {}; +struct LegalTag {}; + +template +class TypedMove { + public: + TypedMove() = default; + + template + requires (std::is_same_v && + std::is_same_v) + [[gnu::always_inline]] constexpr TypedMove(TypedMove move) : move_(move) {} + + [[gnu::always_inline]] constexpr operator const Move&() const { return move_; } + [[gnu::always_inline]] constexpr BitIndex From() const { return move_.From(); } + [[gnu::always_inline]] constexpr BitIndex To() const { return move_.To(); } + [[gnu::always_inline]] constexpr MoveType Type() const { return move_.Type(); } + [[gnu::always_inline]] constexpr Piece PromotionPiece() const { return move_.PromotionPiece(); } + [[gnu::always_inline]] constexpr bool IsValid() const { return move_.IsValid(); } + [[gnu::always_inline]] constexpr bool IsPromotion() const { return move_.IsPromotion(); } + [[gnu::always_inline]] constexpr bool IsEnPassant() const { return move_.IsEnPassant(); } + [[gnu::always_inline]] constexpr bool IsCastling() const { return move_.IsCastling(); } + [[gnu::always_inline]] constexpr bool IsNormal() const { return move_.IsNormal(); } + [[gnu::always_inline]] constexpr std::uint16_t Raw() const { return move_.Raw(); } + [[gnu::always_inline]] constexpr explicit operator bool() const { return static_cast(move_); } + + template + [[gnu::always_inline]] constexpr bool IsQuiet(const PositionType& position) const { + return move_.IsQuiet(position); + } + + [[gnu::always_inline]] constexpr bool operator==(const TypedMove&) const = default; + [[gnu::always_inline]] constexpr bool operator==(const Move& move) const { return move_ == move; } + + template + [[gnu::always_inline]] constexpr bool operator==(const TypedMove& move) const { + return move_ == static_cast(move); + } + + private: + friend class MaybeMove; + friend class Position; + friend class MoveGenerator; + + [[gnu::always_inline]] constexpr explicit TypedMove(Move move) : move_(move) {} + + Move move_; +}; + +using PseudoLegalMove = TypedMove; +using LegalMove = TypedMove; + +static_assert(sizeof(PseudoLegalMove) == sizeof(Move)); +static_assert(sizeof(LegalMove) == sizeof(Move)); +static_assert(alignof(PseudoLegalMove) == alignof(Move)); +static_assert(alignof(LegalMove) == alignof(Move)); +static_assert(std::is_trivially_copyable_v); +static_assert(std::is_trivially_copyable_v); +static_assert(std::is_trivially_default_constructible_v); +static_assert(std::is_trivially_default_constructible_v); +static_assert(std::is_standard_layout_v); +static_assert(std::is_standard_layout_v); +static_assert(std::is_convertible_v); +static_assert(!std::is_constructible_v); +static_assert(!std::is_constructible_v); +static_assert(!std::is_constructible_v); + +template +class MaybeMove { + public: + MaybeMove() = default; + [[gnu::always_inline]] constexpr MaybeMove(TypedMove move) : move_(move) {} + [[gnu::always_inline]] constexpr operator const Move&() const { return move_; } + [[gnu::always_inline]] constexpr explicit operator bool() const { return static_cast(move_).IsValid(); } + template + [[gnu::always_inline]] constexpr bool IsQuiet(const PositionType& position) const { + return static_cast(move_).IsQuiet(position); + } + [[gnu::always_inline]] constexpr bool IsValid() const { return static_cast(move_).IsValid(); } + [[gnu::always_inline]] constexpr const TypedMove& operator*() const { + assert(IsValid()); + return move_; + } + static constexpr MaybeMove None() { return MaybeMove(Move::None()); } + [[gnu::always_inline]] constexpr bool operator==(const MaybeMove&) const = default; + template + [[gnu::always_inline]] constexpr bool operator==(const TypedMove& move) const { + return move_ == static_cast(move); + } + [[gnu::always_inline]] constexpr bool operator==(const Move& move) const { return move_ == move; } + + private: + [[gnu::always_inline]] constexpr explicit MaybeMove(Move move) : move_(move) {} + TypedMove move_; +}; + +using MaybePseudoLegalMove = MaybeMove; +using MaybeLegalMove = MaybeMove; + +static_assert(sizeof(MaybePseudoLegalMove) == sizeof(Move)); +static_assert(sizeof(MaybeLegalMove) == sizeof(Move)); +static_assert(alignof(MaybePseudoLegalMove) == alignof(Move)); +static_assert(alignof(MaybeLegalMove) == alignof(Move)); +static_assert(std::is_trivially_copyable_v); +static_assert(std::is_trivially_copyable_v); +static_assert(std::is_trivially_default_constructible_v); +static_assert(std::is_trivially_default_constructible_v); +static_assert(std::is_standard_layout_v); +static_assert(std::is_standard_layout_v); + +} diff --git a/Chess/UciCommunicator.h b/Chess/UciCommunicator.h index 4786582..bbf81bf 100644 --- a/Chess/UciCommunicator.h +++ b/Chess/UciCommunicator.h @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -698,6 +699,7 @@ class UciChessEngine { void ParseUciNewGame(std::stringstream command); void ParseFen(const std::string& fen); void ParseStartPos(); + [[nodiscard]] std::optional ParseLegalMove(const std::string& text); void ParseMoves(std::stringstream command); void ParsePosition(std::stringstream command); void ParsePerft(std::stringstream command); @@ -863,10 +865,35 @@ inline void UciChessEngine::ParseStartPos() { info_.position = PositionFactory{}(); } +inline bool IsUciMoveText(std::string_view text) { + if (text == "O-O" || text == "O-O-O") return true; + const auto is_file = [](char c) { return c >= 'a' && c <= 'h'; }; + const auto is_rank = [](char c) { return c >= '1' && c <= '8'; }; + const auto is_promotion = [](char c) { + return std::string_view{"qrbnQRBN"}.contains(c); + }; + return (text.size() == 4 || (text.size() == 5 && is_promotion(text[4]))) && + is_file(text[0]) && is_rank(text[1]) && is_file(text[2]) && + is_rank(text[3]); +} + +inline std::optional UciChessEngine::ParseLegalMove( + const std::string& text) { + if (!IsUciMoveText(text)) return std::nullopt; + auto& position = info_.position; + const auto pseudo_legal = position.TryPseudoLegal(MoveFactory{}(position, text)); + return pseudo_legal ? position.TryLegal(*pseudo_legal) : std::nullopt; +} + inline void UciChessEngine::ParseMoves(std::stringstream command) { - std::string move; - while (command >> move) { - info_.position.DoMove(MoveFactory{}(info_.position, move)); + std::string text; + while (command >> text) { + const auto move = ParseLegalMove(text); + if (!move) { + Send("info string illegal move " + text); + break; + } + info_.position.DoMove(*move); } } diff --git a/Tests/CheckedMove.h b/Tests/CheckedMove.h new file mode 100644 index 0000000..3023af3 --- /dev/null +++ b/Tests/CheckedMove.h @@ -0,0 +1,19 @@ +#pragma once + +#include +#include + +#include "MoveFactory.h" +#include "Position.h" + +namespace SimpleChessEngine { + +inline LegalMove CheckedMove(Position& position, const std::string& text) { + const auto pseudo = position.TryPseudoLegal(MoveFactory{}(position, text)); + if (!pseudo) std::abort(); + const auto legal = position.TryLegal(*pseudo); + if (!legal) std::abort(); + return *legal; +} + +} diff --git a/Tests/ChessEngineTests.cpp b/Tests/ChessEngineTests.cpp index 5bf69f8..c9f6a5f 100644 --- a/Tests/ChessEngineTests.cpp +++ b/Tests/ChessEngineTests.cpp @@ -14,6 +14,7 @@ #include "ExitCondition.h" #include "Move.h" #include "MoveFactory.h" +#include "CheckedMove.h" #include "MoveGenerator.h" #include "SimpleChessEngine.h" @@ -47,14 +48,14 @@ TEST(RootRepetition, SearchStillReturnsLegalMove) { auto position = PositionFactory{}(); for (const auto *move : {"g1f3", "g8f6", "f3g1", "f6g8", "g1f3", "g8f6", "f3g1", "f6g8"}) { - position.DoMove(MoveFactory{}(position, move)); + position.DoMove(CheckedMove(position, move)); } std::stringstream ss; ChessEngine engine(position, ss); DepthCondition condition{2}; engine.ComputeBestMove(condition); const auto legal_moves = - MoveGenerator{}.GenerateMoves(position); + MoveGenerator{}.GenerateLegalMoves(position); EXPECT_NE(std::ranges::find(legal_moves, engine.GetCurrentBestMove()), legal_moves.end()); } @@ -91,7 +92,7 @@ TEST(TimeManagement, ReturnsLegalMoveWithoutTime) { TimeCondition condition{std::chrono::milliseconds{0}}; engine.ComputeBestMove(condition); const auto legal = - MoveGenerator{}.GenerateMoves(position); + MoveGenerator{}.GenerateLegalMoves(position); EXPECT_NE(std::ranges::find(legal, engine.GetCurrentBestMove()), legal.end()); EXPECT_EQ(ss.str().find("info depth "), std::string::npos); } diff --git a/Tests/MoveGeneratorTests.cpp b/Tests/MoveGeneratorTests.cpp index b6678be..869c08d 100644 --- a/Tests/MoveGeneratorTests.cpp +++ b/Tests/MoveGeneratorTests.cpp @@ -33,7 +33,7 @@ struct GameInfo { static auto move_generator = MoveGenerator{}; const auto moves = - move_generator.GenerateMoves(position); + move_generator.GenerateLegalMoves(position); if (depth == 1) { for (const auto &move : moves) { diff --git a/Tests/NnueTests.cpp b/Tests/NnueTests.cpp index 3218a02..1920be8 100644 --- a/Tests/NnueTests.cpp +++ b/Tests/NnueTests.cpp @@ -50,12 +50,12 @@ TEST_P(NnueIncremental, RandomGamesMatchFullRefresh) { for (const auto& fen : fens) { for (int game = 0; game < 16; ++game) { Position position = PositionFactory{}(fen); - std::vector> history; + std::vector> history; for (int ply = 0; ply < 160; ++ply) { ASSERT_TRUE(MatchesFullRefresh(position)) << fen << " ply " << ply; ++checked; const auto moves = - MoveGenerator{}.GenerateMoves(position); + MoveGenerator{}.GenerateLegalMoves(position); if (moves.empty()) break; const auto roll = random() % 12; if (roll == 0 && !history.empty()) { diff --git a/Tests/PositionTests.cpp b/Tests/PositionTests.cpp index e03cfc2..5a86b12 100644 --- a/Tests/PositionTests.cpp +++ b/Tests/PositionTests.cpp @@ -3,6 +3,7 @@ #include #include "MoveFactory.h" +#include "CheckedMove.h" #include "MoveGenerator.h" #include "ExitCondition.h" #include "NodeType.h" @@ -19,7 +20,7 @@ TEST(DoMove, DoAndUndoEqualZero) { Position pos = start_pos; for (const auto moves = - MoveGenerator{}.GenerateMoves(pos); + MoveGenerator{}.GenerateLegalMoves(pos); const auto &move : moves) { const auto irreversible_data = pos.GetIrreversibleData(); pos.DoMove(move); @@ -35,7 +36,7 @@ TEST(SomeMoves, DifferentHash) { std::vector moves = {"b1c3", "d7d5", "a1b1"}; std::set hashes = {pos.GetHash()}; for (const auto &move_str : moves) { - auto move = MoveFactory{}(pos, move_str); + auto move = CheckedMove(pos, move_str); pos.DoMove(move); ASSERT_TRUE(hashes.insert(pos.GetHash()).second); } @@ -43,7 +44,7 @@ TEST(SomeMoves, DifferentHash) { Position DoMoves(Position pos, const std::vector &moves) { for (const auto &move_str : moves) { - auto move = MoveFactory{}(pos, move_str); + auto move = CheckedMove(pos, move_str); pos.DoMove(move); } @@ -77,10 +78,10 @@ TEST(FenFactory, PreservesEnPassantSquare) { TEST(FenFactory, UpdatesCountersFromInitialFenState) { auto position = PositionFactory{}( "7k/8/8/8/8/8/8/K7 b - - 37 42"); - position.DoMove(MoveFactory{}(position, "h8g7")); + position.DoMove(CheckedMove(position, "h8g7")); EXPECT_EQ(position.GetHalfMoveClock(), 38); EXPECT_EQ(position.GetFullMoveNumber(), 43); - position.DoMove(MoveFactory{}(position, "a1b1")); + position.DoMove(CheckedMove(position, "a1b1")); EXPECT_EQ(position.GetHalfMoveClock(), 39); EXPECT_EQ(position.GetFullMoveNumber(), 43); } @@ -88,17 +89,17 @@ TEST(FenFactory, UpdatesCountersFromInitialFenState) { TEST(FenFactory, CastlingIgnoresRooksOffTheBackRank) { auto position = PositionFactory{}("3qk2r/prp1pppp/1p1p4/8/8/8/1R2PPPP/4K2R w Kk - 0 1"); - position.DoMove(MoveFactory{}(position, "e1g1")); - position.DoMove(MoveFactory{}(position, "e8g8")); + position.DoMove(CheckedMove(position, "e1g1")); + position.DoMove(CheckedMove(position, "e8g8")); EXPECT_EQ(FenFactory{}(position), "3q1rk1/prp1pppp/1p1p4/8/8/8/1R2PPPP/5RK1 w - - 2 2"); } TEST(FenFactory, CastlingUsesCornerRookWhenAnotherRookShares) { auto position = PositionFactory{}("r1r1k2r/8/8/8/8/8/8/R3K2R b Kq - 0 1"); - position.DoMove(MoveFactory{}(position, "c8c7")); - position.DoMove(MoveFactory{}(position, "e1g1")); - position.DoMove(MoveFactory{}(position, "e8c8")); + position.DoMove(CheckedMove(position, "c8c7")); + position.DoMove(CheckedMove(position, "e1g1")); + position.DoMove(CheckedMove(position, "e8c8")); EXPECT_EQ(FenFactory{}(position), "2kr3r/2r5/8/8/8/8/8/R4RK1 w - - 3 3"); } @@ -112,10 +113,10 @@ TEST(Hash, IncludesCastlingRightsFromFen) { TEST(Hash, LostCastlingRightsMatchFenWithoutThem) { auto position = PositionFactory{}("4k3/8/8/8/8/8/8/4K2R w K - 0 1"); - position.DoMove(MoveFactory{}(position, "h1g1")); - position.DoMove(MoveFactory{}(position, "e8d8")); - position.DoMove(MoveFactory{}(position, "g1h1")); - position.DoMove(MoveFactory{}(position, "d8e8")); + position.DoMove(CheckedMove(position, "h1g1")); + position.DoMove(CheckedMove(position, "e8d8")); + position.DoMove(CheckedMove(position, "g1h1")); + position.DoMove(CheckedMove(position, "d8e8")); const auto expected = PositionFactory{}("4k3/8/8/8/8/8/8/4K2R w - - 4 3"); EXPECT_EQ(position.GetHash(), expected.GetHash()); } @@ -124,14 +125,14 @@ TEST(Repetition, IgnoresEnPassantSquareNobodyCanCapture) { auto position = PositionFactory{}(); for (const auto *move : {"e2e4", "g8f6", "g1f3", "f6g8", "f3g1", "g8f6", "g1f3", "f6g8", "f3g1"}) { - position.DoMove(MoveFactory{}(position, move)); + position.DoMove(CheckedMove(position, move)); } EXPECT_TRUE(position.DetectRepetition(0)); } TEST(Hash, KeepsCapturableEnPassantSquare) { auto position = PositionFactory{}("4k3/8/8/8/3p4/8/4P3/4K3 w - - 0 1"); - position.DoMove(MoveFactory{}(position, "e2e4")); + position.DoMove(CheckedMove(position, "e2e4")); const auto with_square = PositionFactory{}("4k3/8/8/8/3pP3/8/8/4K3 b - e3 0 1"); const auto without_square = @@ -143,10 +144,10 @@ TEST(Hash, KeepsCapturableEnPassantSquare) { TEST(FiftyMoveClock, QuietPromotionResetsCounter) { auto position = PositionFactory{}( "7k/P7/8/8/8/8/8/K7 w - - 99 42"); - position.DoMove(MoveFactory{}(position, "a7a8q")); + position.DoMove(CheckedMove(position, "a7a8q")); EXPECT_EQ(position.GetHalfMoveClock(), 0); EXPECT_EQ(position.GetFullMoveNumber(), 42); - position.DoMove(MoveFactory{}(position, "h8g7")); + position.DoMove(CheckedMove(position, "h8g7")); EXPECT_EQ(position.GetHalfMoveClock(), 1); EXPECT_EQ(position.GetFullMoveNumber(), 43); } @@ -194,7 +195,7 @@ TEST(InsufficientMaterial, SearchReturnsDrawAndLegalRootMove) { ASSERT_TRUE(result.has_value()); EXPECT_EQ(*result, kDrawValue); const auto legal_moves = - MoveGenerator{}.GenerateMoves(position); + MoveGenerator{}.GenerateLegalMoves(position); EXPECT_NE(std::ranges::find(legal_moves, searcher.GetCurrentBestMove()), legal_moves.end()); } @@ -261,7 +262,7 @@ TEST(TranspositionTable, IllegalStoredMoveIsIgnored) { ASSERT_TRUE(result.has_value()); const auto legal_moves = - MoveGenerator{}.GenerateMoves(position); + MoveGenerator{}.GenerateLegalMoves(position); EXPECT_NE(std::ranges::find(legal_moves, searcher.GetCurrentBestMove()), legal_moves.end()); } diff --git a/Tests/SearchCorrectnessTests.cpp b/Tests/SearchCorrectnessTests.cpp index 3bb818d..b680211 100644 --- a/Tests/SearchCorrectnessTests.cpp +++ b/Tests/SearchCorrectnessTests.cpp @@ -7,6 +7,7 @@ #include "ExitCondition.h" #include "MoveFactory.h" +#include "CheckedMove.h" #include "Nnue/Nnue.h" #include "PositionFactory.h" #include "Quiescence.h" @@ -26,7 +27,7 @@ TEST(QuiescenceDraws, RepetitionInGameHistory) { auto position = PositionFactory{}("7k/8/6K1/8/8/8/8/1Q6 w - - 0 1"); for (const auto* move : {"b1b2", "h8g8", "b2b1", "g8h8", "b1b2", "h8g8", "b2b1", "g8h8"}) { - position.DoMove(MoveFactory{}(position, move)); + position.DoMove(CheckedMove(position, move)); } ASSERT_TRUE(position.DetectRepetition(0)); DepthCondition condition{4}; @@ -38,7 +39,7 @@ TEST(QuiescenceDraws, RepetitionInGameHistory) { TEST(QuiescenceDraws, StalemateWithPinnedBishop) { auto position = PositionFactory{}("7k/5K1b/7Q/8/8/8/8/8 b - - 0 1"); ASSERT_FALSE(position.IsUnderCheck()); - ASSERT_TRUE(MoveGenerator{}.GenerateMoves(position) + ASSERT_TRUE(MoveGenerator{}.GenerateLegalMoves(position) .empty()); DepthCondition condition{4}; Quiescence search{condition}; @@ -100,7 +101,7 @@ TEST(SingularExtensions, ExclusionIgnoresBoundsAndPreservesFullNodeEntry) { TEST(SingularExtensions, ExcludingOnlyEvasionReturnsFailLow) { auto position = PositionFactory{}("r7/8/8/8/8/2k5/8/K7 w - - 0 1"); const auto moves = - MoveGenerator{}.GenerateMoves(position); + MoveGenerator{}.GenerateLegalMoves(position); ASSERT_EQ(moves.size(), 1u); ASSERT_TRUE(position.IsUnderCheck()); Searcher searcher(position); diff --git a/Tests/StagedMovePickerTests.cpp b/Tests/StagedMovePickerTests.cpp index 03d9c8c..73e5177 100644 --- a/Tests/StagedMovePickerTests.cpp +++ b/Tests/StagedMovePickerTests.cpp @@ -30,7 +30,7 @@ constexpr std::array kPositions = { std::set LegalSet(Position& position) { std::set result; for (auto move : - MoveGenerator{}.GenerateMoves(position)) { + MoveGenerator{}.GenerateLegalMoves(position)) { result.insert(move.Raw()); } return result; @@ -41,7 +41,7 @@ TEST(StagedMovePicker, PseudoLegalValidationMatchesGenerator) { for (const auto* fen : kPositions) { SCOPED_TRACE(fen); auto position = PositionFactory{}(fen); - std::array generated; + std::array generated; auto* end = MoveGenerator{}.GeneratePseudoLegal( position, generated.data()); std::set expected; @@ -59,7 +59,7 @@ TEST(StagedMovePicker, CaptureAndQuietStagesPartitionLegalMoves) { SCOPED_TRACE(fen); auto position = PositionFactory{}(fen); const auto expected = LegalSet(position); - std::array generated; + std::array generated; auto* middle = MoveGenerator{}.GeneratePseudoLegal( position, generated.data()); @@ -92,14 +92,15 @@ TEST(StagedMovePicker, MainSearchEmitsLegalMovesOnceWithTtFirst) { std::set actual; auto move = picker.SelectNextMove(); if (expected.contains(tt.Raw())) { - EXPECT_EQ(move, tt); + ASSERT_TRUE(move); + EXPECT_EQ(*move, tt); } - for (; move.IsValid(); move = picker.SelectNextMove()) { - ASSERT_TRUE(expected.contains(move.Raw())); - EXPECT_TRUE(actual.insert(move.Raw()).second); - position.DoMove(move); + for (; move; move = picker.SelectNextMove()) { + ASSERT_TRUE(expected.contains((*move).Raw())); + EXPECT_TRUE(actual.insert((*move).Raw()).second); + position.DoMove(*move); position.ComputePins(position.GetSideToMove()); - position.UndoMove(move, uncomputed_data); + position.UndoMove(*move, uncomputed_data); } EXPECT_EQ(actual, expected); EXPECT_EQ(picker.MoveCount(), expected.size()); @@ -113,12 +114,16 @@ TEST(StagedMovePicker, QuiescencePreservesGeneratorOrderAndEvasions) { auto position = PositionFactory{}(fen); const auto expected = position.IsUnderCheck() - ? MoveGenerator{}.GenerateMoves(position) - : MoveGenerator{}.GenerateMoves( + ? MoveGenerator{}.GenerateLegalMoves(position) + : MoveGenerator{}.GenerateLegalMoves( position); MovePicker picker; picker.InitPicker(position, nullptr, 0); - for (auto move : expected) EXPECT_EQ(picker.SelectNextMove(), move); - EXPECT_EQ(picker.SelectNextMove(), Move::None()); + for (auto move : expected) { + const auto selected = picker.SelectNextMove(); + ASSERT_TRUE(selected); + EXPECT_EQ(*selected, move); + } + EXPECT_FALSE(picker.SelectNextMove()); } } diff --git a/Tests/TypedMoveTests.cpp b/Tests/TypedMoveTests.cpp new file mode 100644 index 0000000..e4e80a9 --- /dev/null +++ b/Tests/TypedMoveTests.cpp @@ -0,0 +1,107 @@ +#include + +#include +#include + +#include "MoveFactory.h" +#include "MoveGenerator.h" +#include "MovePicker.h" +#include "PositionFactory.h" +#include "TypedMove.h" + +using namespace SimpleChessEngine; + +template +concept CanDoMove = requires(Position& position, M move) { + position.DoMove(move); +}; + +template +concept CanUndoMove = requires(Position& position, M move) { + position.UndoMove(move, position.GetIrreversibleData()); +}; + +template +concept CanConstructLegalMove = requires(M move) { + LegalMove(move); +}; + +static_assert(CanDoMove); +static_assert(CanUndoMove); +static_assert(!CanDoMove); +static_assert(!CanDoMove); +static_assert(!CanDoMove); +static_assert(!CanUndoMove); +static_assert(!CanUndoMove); +static_assert(!CanUndoMove); +static_assert(std::is_same_v().SelectNextMove()), MaybeLegalMove>); +static_assert(!CanConstructLegalMove); +static_assert(!CanConstructLegalMove); +static_assert(!std::is_constructible_v); +static_assert(!std::is_constructible_v); +static_assert(!static_cast(MaybeLegalMove::None())); +static_assert(!static_cast(MaybePseudoLegalMove::None())); +static_assert(sizeof(PseudoLegalMove) == sizeof(Move)); +static_assert(sizeof(LegalMove) == sizeof(Move)); +static_assert(alignof(PseudoLegalMove) == alignof(Move)); +static_assert(alignof(LegalMove) == alignof(Move)); +static_assert(std::is_trivially_copyable_v); +static_assert(std::is_trivially_copyable_v); +static_assert(std::is_trivially_default_constructible_v); +static_assert(std::is_trivially_default_constructible_v); +static_assert(std::is_standard_layout_v); +static_assert(std::is_standard_layout_v); +static_assert(std::is_convertible_v); +static_assert(!std::is_constructible_v); +static_assert(!std::is_constructible_v); +static_assert(!std::is_constructible_v); + +TEST(TypedMoves, RejectsGarbage) { + auto position = PositionFactory{}(); + EXPECT_FALSE(position.TryPseudoLegal(Move(0xffff))); + EXPECT_FALSE(position.TryPseudoLegal(Move::None())); + EXPECT_FALSE(position.TryPseudoLegal(Move::Null())); + EXPECT_FALSE(position.TryPseudoLegal(MoveFactory{}(position, "a1a8"))); +} + +TEST(TypedMoves, RejectsExposingKing) { + auto position = PositionFactory{}("4r1k1/8/8/8/8/8/4R3/4K3 w - - 0 1"); + const auto pseudo = position.TryPseudoLegal(MoveFactory{}(position, "e2f2")); + ASSERT_TRUE(pseudo); + EXPECT_FALSE(position.TryLegal(*pseudo)); + EXPECT_FALSE(position.TryLegal(*pseudo, position.GetIrreversibleData().blockers[0])); +} + +TEST(TypedMoves, AcceptsEveryGeneratedLegalMove) { + for (const auto* fen : { + "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", + "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1", + "4k3/8/8/r4pPK/8/8/8/8 w - f6 0 1", + "4k3/P7/8/8/8/8/7p/4K3 w - - 0 1", + "4k3/8/8/8/8/8/8/6KR w H - 0 1"}) { + auto position = PositionFactory{}(fen); + const auto moves = MoveGenerator{}.GenerateLegalMoves(position); + const auto raw_moves = MoveGenerator{}.GenerateMoves(position); + ASSERT_EQ(moves.size(), raw_moves.size()); + for (size_t i = 0; i < moves.size(); ++i) EXPECT_EQ(moves[i], raw_moves[i]); + for (const auto move : moves) { + const Move raw = move; + const PseudoLegalMove degraded = move; + EXPECT_EQ(degraded, raw); + EXPECT_EQ(raw, degraded); + EXPECT_EQ(move, raw); + EXPECT_EQ(raw, move); + EXPECT_EQ(move, degraded); + const auto pseudo = position.TryPseudoLegal(raw); + ASSERT_TRUE(pseudo); + EXPECT_EQ(*pseudo, degraded); + const auto legal = position.TryLegal(*pseudo); + ASSERT_TRUE(legal); + EXPECT_EQ(*legal, move); + const auto explicit_blockers = position.TryLegal( + *pseudo, position.GetIrreversibleData().blockers[static_cast(position.GetSideToMove())]); + ASSERT_TRUE(explicit_blockers); + EXPECT_EQ(*explicit_blockers, move); + } + } +}