]> git.sesse.net Git - stockfish/blobdiff - src/position.cpp
Document index[] and pieceList[] are not invariants
[stockfish] / src / position.cpp
index 5f1f843b2b075d683b7b1aa1d154335e6e4932b3..c673225737b2906d428743b8a6f034d60d75d1c9 100644 (file)
@@ -710,7 +710,6 @@ void Position::do_move(Move m, StateInfo& newSt, Bitboard dcCandidates) {
   };
 
   memcpy(&newSt, st, sizeof(ReducedStateInfo));
-  newSt.capture = NO_PIECE_TYPE;
   newSt.previous = st;
   st = &newSt;
 
@@ -764,7 +763,8 @@ void Position::do_move(Move m, StateInfo& newSt, Bitboard dcCandidates) {
   }
 
   // Update castle rights, try to shortcut a common case
-  if ((castleRightsMask[from] & castleRightsMask[to]) != ALL_CASTLES)
+  int cm = castleRightsMask[from] & castleRightsMask[to];
+  if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
   {
       key ^= zobCastle[st->castleRights];
       st->castleRights &= castleRightsMask[from];
@@ -788,9 +788,11 @@ void Position::do_move(Move m, StateInfo& newSt, Bitboard dcCandidates) {
   if (pt == KING)
       kingSquare[us] = to;
 
-  // Update piece lists
-  pieceList[us][pt][index[from]] = to;
+  // Update piece lists, note that index[from] is not updated and
+  // becomes stale. This works as long as index[] is accessed just
+  // by known occupied squares.
   index[to] = index[from];
+  pieceList[us][pt][index[to]] = to;
 
   // If the moving piece was a pawn do some special extra work
   if (pt == PAWN)
@@ -804,9 +806,8 @@ void Position::do_move(Move m, StateInfo& newSt, Bitboard dcCandidates) {
       // Set en passant square, only if moved pawn can be captured
       if (abs(int(to) - int(from)) == 16)
       {
-          if (   (us == WHITE && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
-              || (us == BLACK && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
-              {
+          if (pawn_attacks(us, from + (us == WHITE ? DELTA_N : DELTA_S)) & pawns(them))
+          {
               st->epSquare = Square((int(from) + int(to)) / 2);
               key ^= zobEp[st->epSquare];
           }
@@ -817,7 +818,7 @@ void Position::do_move(Move m, StateInfo& newSt, Bitboard dcCandidates) {
   st->mgValue += pst_delta<MidGame>(piece, from, to);
   st->egValue += pst_delta<EndGame>(piece, from, to);
 
-  if (pm)
+  if (pm) // promotion ?
   {
       PieceType promotion = move_promotion_piece(m);
 
@@ -828,24 +829,26 @@ void Position::do_move(Move m, StateInfo& newSt, Bitboard dcCandidates) {
       set_bit(&(byTypeBB[promotion]), to);
       board[to] = piece_of_color_and_type(us, promotion);
 
+      // Update material key
+      st->materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
+      st->materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
+
       // Update piece counts
       pieceCount[us][PAWN]--;
       pieceCount[us][promotion]++;
 
-      // Update piece lists
-      pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
-      index[pieceList[us][PAWN][index[from]]] = index[from];
-      pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
+      // Update piece lists, move the last pawn at index[to] position
+      // and shrink the list. Add a new promotion piece to the list.
+      Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
+      index[lastPawnSquare] = index[to];
+      pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
       index[to] = pieceCount[us][promotion] - 1;
+      pieceList[us][promotion][index[to]] = to;
 
       // Partially revert hash keys update
       key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
       st->pawnKey ^= zobrist[us][PAWN][to];
 
-      // Update material key
-      st->materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
-      st->materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
-
       // Partially revert and update incremental scores
       st->mgValue -= pst<MidGame>(us, PAWN, to);
       st->mgValue += pst<MidGame>(us, promotion, to);
@@ -883,6 +886,8 @@ void Position::do_move(Move m, StateInfo& newSt, Bitboard dcCandidates) {
 
   st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
   st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
+
+  assert(is_ok());
 }
 
 
@@ -895,14 +900,13 @@ void Position::do_capture_move(Bitboard& key, PieceType capture, Color them, Squ
 
     Square capsq = to;
 
-    if (ep)
+    if (ep) // en passant ?
     {
         capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
 
         assert(to == st->epSquare);
         assert(relative_rank(opposite_color(them), to) == RANK_6);
         assert(piece_on(to) == EMPTY);
-        assert(piece_on(from) == piece_of_color_and_type(opposite_color(them), PAWN));
         assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
 
         board[capsq] = EMPTY;
@@ -934,9 +938,16 @@ void Position::do_capture_move(Bitboard& key, PieceType capture, Color them, Squ
     // Update piece count
     pieceCount[them][capture]--;
 
-    // Update piece list
-    pieceList[them][capture][index[capsq]] = pieceList[them][capture][pieceCount[them][capture]];
-    index[pieceList[them][capture][index[capsq]]] = index[capsq];
+    // Update piece list, move the last piece at index[capsq] position
+    //
+    // WARNING: this is a not perfectly revresible operation. When we
+    // will reinsert the captured piece in undo_move() we will put it
+    // at the end of the list and not in its original place, it means
+    // index[] and pieceList[] are not guaranteed to be invariant to a
+    // do_move() + undo_move() sequence.
+    Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
+    index[lastPieceSquare] = index[capsq];
+    pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
 
     // Reset rule 50 counter
     st->rule50 = 0;
@@ -950,13 +961,15 @@ void Position::do_capture_move(Bitboard& key, PieceType capture, Color them, Squ
 
 void Position::do_castle_move(Move m) {
 
-  assert(is_ok());
   assert(move_is_ok(m));
   assert(move_is_castle(m));
 
   Color us = side_to_move();
   Color them = opposite_color(us);
 
+  // Reset capture field
+  st->capture = NO_PIECE_TYPE;
+
   // Find source squares for king and rook
   Square kfrom = move_from(m);
   Square rfrom = move_to(m);  // HACK: See comment at beginning of function
@@ -999,7 +1012,7 @@ void Position::do_castle_move(Move m) {
   // Update piece lists
   pieceList[us][KING][index[kfrom]] = kto;
   pieceList[us][ROOK][index[rfrom]] = rto;
-  int tmp = index[rfrom];
+  int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
   index[kto] = index[kfrom];
   index[rto] = tmp;
 
@@ -1036,6 +1049,8 @@ void Position::do_castle_move(Move m) {
 
   st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
   st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
+
+  assert(is_ok());
 }
 
 
@@ -1072,7 +1087,7 @@ void Position::undo_move(Move m) {
   assert(!ep || relative_rank(us, to) == RANK_6);
   assert(!ep || piece_on(to) == piece_of_color_and_type(us, PAWN));
 
-  if (pm)
+  if (pm) // promotion ?
   {
       PieceType promotion = move_promotion_piece(m);
       pt = PAWN;
@@ -1089,10 +1104,11 @@ void Position::undo_move(Move m) {
       pieceCount[us][PAWN]++;
 
       // Update piece list replacing promotion piece with a pawn
-      pieceList[us][promotion][index[to]] = pieceList[us][promotion][pieceCount[us][promotion]];
-      index[pieceList[us][promotion][index[to]]] = index[to];
-      pieceList[us][PAWN][pieceCount[us][PAWN] - 1] = to;
+      Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
+      index[lastPromotionSquare] = index[to];
+      pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
       index[to] = pieceCount[us][PAWN] - 1;
+      pieceList[us][PAWN][index[to]] = to;
   }
 
   // Put the piece back at the source square
@@ -1109,8 +1125,8 @@ void Position::undo_move(Move m) {
       kingSquare[us] = from;
 
   // Update piece list
-  pieceList[us][pt][index[to]] = from;
   index[from] = index[to];
+  pieceList[us][pt][index[from]] = from;
 
   if (st->capture)
   {
@@ -1129,16 +1145,18 @@ void Position::undo_move(Move m) {
 
       board[capsq] = piece_of_color_and_type(them, st->capture);
 
-      // Update piece list
-      pieceList[them][st->capture][pieceCount[them][st->capture]] = capsq;
-      index[capsq] = pieceCount[them][st->capture];
-
       // Update piece count
       pieceCount[them][st->capture]++;
+
+      // Update piece list, add a new captured piece in capsq square
+      index[capsq] = pieceCount[them][st->capture] - 1;
+      pieceList[them][st->capture][index[capsq]] = capsq;
   }
 
   // Finally point our state pointer back to the previous state
   st = st->previous;
+
+  assert(is_ok());
 }
 
 
@@ -1197,12 +1215,14 @@ void Position::undo_castle_move(Move m) {
   // Update piece lists
   pieceList[us][KING][index[kto]] = kfrom;
   pieceList[us][ROOK][index[rto]] = rfrom;
-  int tmp = index[rto];  // Necessary because we may have rto == kfrom in FRC.
+  int tmp = index[rto];  // In Chess960 could be rto == kfrom
   index[kfrom] = index[kto];
   index[rfrom] = tmp;
 
   // Finally point our state pointer back to the previous state
   st = st->previous;
+
+  assert(is_ok());
 }
 
 
@@ -1218,10 +1238,10 @@ void Position::do_null_move(StateInfo& backupSt) {
   // StateInfo object.
   // Note that differently from normal case here backupSt is actually used as
   // a backup storage not as a new state to be used.
+  backupSt.key      = st->key;
   backupSt.epSquare = st->epSquare;
-  backupSt.key = st->key;
-  backupSt.mgValue = st->mgValue;
-  backupSt.egValue = st->egValue;
+  backupSt.mgValue  = st->mgValue;
+  backupSt.egValue  = st->egValue;
   backupSt.previous = st->previous;
   st->previous = &backupSt;
 
@@ -1235,6 +1255,7 @@ void Position::do_null_move(StateInfo& backupSt) {
 
   st->key ^= zobSideToMove;
   TT.prefetch(st->key);
+
   sideToMove = opposite_color(sideToMove);
   st->epSquare = SQ_NONE;
   st->rule50++;
@@ -1242,8 +1263,6 @@ void Position::do_null_move(StateInfo& backupSt) {
 
   st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
   st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
-
-  assert(is_ok());
 }
 
 
@@ -1255,18 +1274,17 @@ void Position::undo_null_move() {
   assert(!is_check());
 
   // Restore information from the our backup StateInfo object
-  st->epSquare = st->previous->epSquare;
-  st->key = st->previous->key;
-  st->mgValue = st->previous->mgValue;
-  st->egValue = st->previous->egValue;
-  st->previous = st->previous->previous;
+  StateInfo* backupSt = st->previous;
+  st->key      = backupSt->key;
+  st->epSquare = backupSt->epSquare;
+  st->mgValue  = backupSt->mgValue;
+  st->egValue  = backupSt->egValue;
+  st->previous = backupSt->previous;
 
   // Update the necessary information
   sideToMove = opposite_color(sideToMove);
   st->rule50--;
   gamePly--;
-
-  assert(is_ok());
 }
 
 
@@ -1459,19 +1477,17 @@ void Position::clear() {
   memset(st, 0, sizeof(StateInfo));
   st->epSquare = SQ_NONE;
 
-  memset(index, 0, sizeof(int) * 64);
-  memset(byColorBB, 0, sizeof(Bitboard) * 2);
+  memset(byColorBB,  0, sizeof(Bitboard) * 2);
+  memset(byTypeBB,   0, sizeof(Bitboard) * 8);
+  memset(pieceCount, 0, sizeof(int) * 2 * 8);
+  memset(index,      0, sizeof(int) * 64);
 
   for (int i = 0; i < 64; i++)
       board[i] = EMPTY;
 
   for (int i = 0; i < 7; i++)
-  {
-      byTypeBB[i] = EmptyBoardBB;
-      pieceCount[0][i] = pieceCount[1][i] = 0;
       for (int j = 0; j < 8; j++)
           pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
-  }
 
   sideToMove = WHITE;
   gamePly = 0;
@@ -1686,7 +1702,7 @@ bool Position::is_mate() const {
 
   MoveStack moves[256];
 
-  return is_check() && !generate_evasions(*this, moves, pinned_pieces(sideToMove));
+  return is_check() && (generate_evasions(*this, moves, pinned_pieces(sideToMove)) == moves);
 }
 
 
@@ -1706,20 +1722,18 @@ bool Position::has_mate_threat(Color c) {
       do_null_move(st1);
 
   MoveStack mlist[120];
-  int count;
   bool result = false;
   Bitboard dc = discovered_check_candidates(sideToMove);
   Bitboard pinned = pinned_pieces(sideToMove);
 
   // Generate pseudo-legal non-capture and capture check moves
-  count = generate_non_capture_checks(*this, mlist, dc);
-  count += generate_captures(*this, mlist + count);
+  MoveStack* last = generate_non_capture_checks(*this, mlist, dc);
+  last = generate_captures(*this, last);
 
   // Loop through the moves, and see if one of them is mate
-  for (int i = 0; i < count; i++)
+  for (MoveStack* cur = mlist; cur != last; cur++)
   {
-      Move move = mlist[i].move;
-
+      Move move = cur->move;
       if (!pl_move_is_legal(move, pinned))
           continue;