]> git.sesse.net Git - stockfish/blob - src/position.cpp
FEN parsing: add a second check for correctly setting e.p. square
[stockfish] / src / position.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4   Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
5   Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad
6
7   Stockfish is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
11
12   Stockfish is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include <algorithm>
22 #include <cassert>
23 #include <cstddef> // For offsetof()
24 #include <cstring> // For std::memset, std::memcmp
25 #include <iomanip>
26 #include <sstream>
27
28 #include "bitboard.h"
29 #include "misc.h"
30 #include "movegen.h"
31 #include "position.h"
32 #include "thread.h"
33 #include "tt.h"
34 #include "uci.h"
35 #include "syzygy/tbprobe.h"
36
37 using std::string;
38
39 namespace PSQT {
40   extern Score psq[PIECE_NB][SQUARE_NB];
41 }
42
43 namespace Zobrist {
44
45   Key psq[PIECE_NB][SQUARE_NB];
46   Key enpassant[FILE_NB];
47   Key castling[CASTLING_RIGHT_NB];
48   Key side;
49 }
50
51 namespace {
52
53 const string PieceToChar(" PNBRQK  pnbrqk");
54
55 // min_attacker() is a helper function used by see_ge() to locate the least
56 // valuable attacker for the side to move, remove the attacker we just found
57 // from the bitboards and scan for new X-ray attacks behind it.
58
59 template<int Pt>
60 PieceType min_attacker(const Bitboard* bb, Square to, Bitboard stmAttackers,
61                        Bitboard& occupied, Bitboard& attackers) {
62
63   Bitboard b = stmAttackers & bb[Pt];
64   if (!b)
65       return min_attacker<Pt+1>(bb, to, stmAttackers, occupied, attackers);
66
67   occupied ^= b & ~(b - 1);
68
69   if (Pt == PAWN || Pt == BISHOP || Pt == QUEEN)
70       attackers |= attacks_bb<BISHOP>(to, occupied) & (bb[BISHOP] | bb[QUEEN]);
71
72   if (Pt == ROOK || Pt == QUEEN)
73       attackers |= attacks_bb<ROOK>(to, occupied) & (bb[ROOK] | bb[QUEEN]);
74
75   attackers &= occupied; // After X-ray that may add already processed pieces
76   return (PieceType)Pt;
77 }
78
79 template<>
80 PieceType min_attacker<KING>(const Bitboard*, Square, Bitboard, Bitboard&, Bitboard&) {
81   return KING; // No need to update bitboards: it is the last cycle
82 }
83
84 } // namespace
85
86
87 /// operator<<(Position) returns an ASCII representation of the position
88
89 std::ostream& operator<<(std::ostream& os, Position& pos) {
90
91   os << "\n +---+---+---+---+---+---+---+---+\n";
92
93   for (Rank r = RANK_8; r >= RANK_1; --r)
94   {
95       for (File f = FILE_A; f <= FILE_H; ++f)
96           os << " | " << PieceToChar[pos.piece_on(make_square(f, r))];
97
98       os << " |\n +---+---+---+---+---+---+---+---+\n";
99   }
100
101   os << "\nFen: " << pos.fen() << "\nKey: " << std::hex << std::uppercase
102      << std::setfill('0') << std::setw(16) << pos.key()
103      << std::setfill(' ') << std::dec << "\nCheckers: ";
104
105   for (Bitboard b = pos.checkers(); b; )
106       os << UCI::square(pop_lsb(&b)) << " ";
107
108   if (    int(Tablebases::MaxCardinality) >= popcount(pos.pieces())
109       && !pos.can_castle(ANY_CASTLING))
110   {
111       Tablebases::ProbeState s1, s2;
112       Tablebases::WDLScore wdl = Tablebases::probe_wdl(pos, &s1);
113       int dtz = Tablebases::probe_dtz(pos, &s2);
114       os << "\nTablebases WDL: " << std::setw(4) << wdl << " (" << s1 << ")"
115          << "\nTablebases DTZ: " << std::setw(4) << dtz << " (" << s2 << ")";
116   }
117
118   return os;
119 }
120
121
122 /// Position::init() initializes at startup the various arrays used to compute
123 /// hash keys.
124
125 void Position::init() {
126
127   PRNG rng(1070372);
128
129   for (Piece pc : Pieces)
130       for (Square s = SQ_A1; s <= SQ_H8; ++s)
131           Zobrist::psq[pc][s] = rng.rand<Key>();
132
133   for (File f = FILE_A; f <= FILE_H; ++f)
134       Zobrist::enpassant[f] = rng.rand<Key>();
135
136   for (int cr = NO_CASTLING; cr <= ANY_CASTLING; ++cr)
137   {
138       Zobrist::castling[cr] = 0;
139       Bitboard b = cr;
140       while (b)
141       {
142           Key k = Zobrist::castling[1ULL << pop_lsb(&b)];
143           Zobrist::castling[cr] ^= k ? k : rng.rand<Key>();
144       }
145   }
146
147   Zobrist::side = rng.rand<Key>();
148 }
149
150
151 /// Position::set() initializes the position object with the given FEN string.
152 /// This function is not very robust - make sure that input FENs are correct,
153 /// this is assumed to be the responsibility of the GUI.
154
155 Position& Position::set(const string& fenStr, bool isChess960, StateInfo* si, Thread* th) {
156 /*
157    A FEN string defines a particular position using only the ASCII character set.
158
159    A FEN string contains six fields separated by a space. The fields are:
160
161    1) Piece placement (from white's perspective). Each rank is described, starting
162       with rank 8 and ending with rank 1. Within each rank, the contents of each
163       square are described from file A through file H. Following the Standard
164       Algebraic Notation (SAN), each piece is identified by a single letter taken
165       from the standard English names. White pieces are designated using upper-case
166       letters ("PNBRQK") whilst Black uses lowercase ("pnbrqk"). Blank squares are
167       noted using digits 1 through 8 (the number of blank squares), and "/"
168       separates ranks.
169
170    2) Active color. "w" means white moves next, "b" means black.
171
172    3) Castling availability. If neither side can castle, this is "-". Otherwise,
173       this has one or more letters: "K" (White can castle kingside), "Q" (White
174       can castle queenside), "k" (Black can castle kingside), and/or "q" (Black
175       can castle queenside).
176
177    4) En passant target square (in algebraic notation). If there's no en passant
178       target square, this is "-". If a pawn has just made a 2-square move, this
179       is the position "behind" the pawn. This is recorded only if there is a pawn
180       in position to make an en passant capture, and if there really is a pawn
181       that might have advanced two squares.
182
183    5) Halfmove clock. This is the number of halfmoves since the last pawn advance
184       or capture. This is used to determine if a draw can be claimed under the
185       fifty-move rule.
186
187    6) Fullmove number. The number of the full move. It starts at 1, and is
188       incremented after Black's move.
189 */
190
191   unsigned char col, row, token;
192   size_t idx;
193   Square sq = SQ_A8;
194   std::istringstream ss(fenStr);
195
196   std::memset(this, 0, sizeof(Position));
197   std::memset(si, 0, sizeof(StateInfo));
198   std::fill_n(&pieceList[0][0], sizeof(pieceList) / sizeof(Square), SQ_NONE);
199   st = si;
200
201   ss >> std::noskipws;
202
203   // 1. Piece placement
204   while ((ss >> token) && !isspace(token))
205   {
206       if (isdigit(token))
207           sq += Square(token - '0'); // Advance the given number of files
208
209       else if (token == '/')
210           sq -= Square(16);
211
212       else if ((idx = PieceToChar.find(token)) != string::npos)
213       {
214           put_piece(Piece(idx), sq);
215           ++sq;
216       }
217   }
218
219   // 2. Active color
220   ss >> token;
221   sideToMove = (token == 'w' ? WHITE : BLACK);
222   ss >> token;
223
224   // 3. Castling availability. Compatible with 3 standards: Normal FEN standard,
225   // Shredder-FEN that uses the letters of the columns on which the rooks began
226   // the game instead of KQkq and also X-FEN standard that, in case of Chess960,
227   // if an inner rook is associated with the castling right, the castling tag is
228   // replaced by the file letter of the involved rook, as for the Shredder-FEN.
229   while ((ss >> token) && !isspace(token))
230   {
231       Square rsq;
232       Color c = islower(token) ? BLACK : WHITE;
233       Piece rook = make_piece(c, ROOK);
234
235       token = char(toupper(token));
236
237       if (token == 'K')
238           for (rsq = relative_square(c, SQ_H1); piece_on(rsq) != rook; --rsq) {}
239
240       else if (token == 'Q')
241           for (rsq = relative_square(c, SQ_A1); piece_on(rsq) != rook; ++rsq) {}
242
243       else if (token >= 'A' && token <= 'H')
244           rsq = make_square(File(token - 'A'), relative_rank(c, RANK_1));
245
246       else
247           continue;
248
249       set_castling_right(c, rsq);
250   }
251
252   // 4. En passant square. Ignore if no pawn capture is possible
253   if (   ((ss >> col) && (col >= 'a' && col <= 'h'))
254       && ((ss >> row) && (row == '3' || row == '6')))
255   {
256       st->epSquare = make_square(File(col - 'a'), Rank(row - '1'));
257
258       if (   !(attackers_to(st->epSquare) & pieces(sideToMove, PAWN))
259           || !(pieces(~sideToMove, PAWN) & (st->epSquare + pawn_push(~sideToMove))))
260           st->epSquare = SQ_NONE;
261   }
262   else
263       st->epSquare = SQ_NONE;
264
265   // 5-6. Halfmove clock and fullmove number
266   ss >> std::skipws >> st->rule50 >> gamePly;
267
268   // Convert from fullmove starting from 1 to ply starting from 0,
269   // handle also common incorrect FEN with fullmove = 0.
270   gamePly = std::max(2 * (gamePly - 1), 0) + (sideToMove == BLACK);
271
272   chess960 = isChess960;
273   thisThread = th;
274   set_state(st);
275
276   assert(pos_is_ok());
277
278   return *this;
279 }
280
281
282 /// Position::set_castling_right() is a helper function used to set castling
283 /// rights given the corresponding color and the rook starting square.
284
285 void Position::set_castling_right(Color c, Square rfrom) {
286
287   Square kfrom = square<KING>(c);
288   CastlingSide cs = kfrom < rfrom ? KING_SIDE : QUEEN_SIDE;
289   CastlingRight cr = (c | cs);
290
291   st->castlingRights |= cr;
292   castlingRightsMask[kfrom] |= cr;
293   castlingRightsMask[rfrom] |= cr;
294   castlingRookSquare[cr] = rfrom;
295
296   Square kto = relative_square(c, cs == KING_SIDE ? SQ_G1 : SQ_C1);
297   Square rto = relative_square(c, cs == KING_SIDE ? SQ_F1 : SQ_D1);
298
299   for (Square s = std::min(rfrom, rto); s <= std::max(rfrom, rto); ++s)
300       if (s != kfrom && s != rfrom)
301           castlingPath[cr] |= s;
302
303   for (Square s = std::min(kfrom, kto); s <= std::max(kfrom, kto); ++s)
304       if (s != kfrom && s != rfrom)
305           castlingPath[cr] |= s;
306 }
307
308
309 /// Position::set_check_info() sets king attacks to detect if a move gives check
310
311 void Position::set_check_info(StateInfo* si) const {
312
313   si->blockersForKing[WHITE] = slider_blockers(pieces(BLACK), square<KING>(WHITE), si->pinnersForKing[WHITE]);
314   si->blockersForKing[BLACK] = slider_blockers(pieces(WHITE), square<KING>(BLACK), si->pinnersForKing[BLACK]);
315
316   Square ksq = square<KING>(~sideToMove);
317
318   si->checkSquares[PAWN]   = attacks_from<PAWN>(ksq, ~sideToMove);
319   si->checkSquares[KNIGHT] = attacks_from<KNIGHT>(ksq);
320   si->checkSquares[BISHOP] = attacks_from<BISHOP>(ksq);
321   si->checkSquares[ROOK]   = attacks_from<ROOK>(ksq);
322   si->checkSquares[QUEEN]  = si->checkSquares[BISHOP] | si->checkSquares[ROOK];
323   si->checkSquares[KING]   = 0;
324 }
325
326
327 /// Position::set_state() computes the hash keys of the position, and other
328 /// data that once computed is updated incrementally as moves are made.
329 /// The function is only used when a new position is set up, and to verify
330 /// the correctness of the StateInfo data when running in debug mode.
331
332 void Position::set_state(StateInfo* si) const {
333
334   si->key = si->pawnKey = si->materialKey = 0;
335   si->nonPawnMaterial[WHITE] = si->nonPawnMaterial[BLACK] = VALUE_ZERO;
336   si->psq = SCORE_ZERO;
337   si->checkersBB = attackers_to(square<KING>(sideToMove)) & pieces(~sideToMove);
338
339   set_check_info(si);
340
341   for (Bitboard b = pieces(); b; )
342   {
343       Square s = pop_lsb(&b);
344       Piece pc = piece_on(s);
345       si->key ^= Zobrist::psq[pc][s];
346       si->psq += PSQT::psq[pc][s];
347   }
348
349   if (si->epSquare != SQ_NONE)
350       si->key ^= Zobrist::enpassant[file_of(si->epSquare)];
351
352   if (sideToMove == BLACK)
353       si->key ^= Zobrist::side;
354
355   si->key ^= Zobrist::castling[si->castlingRights];
356
357   for (Bitboard b = pieces(PAWN); b; )
358   {
359       Square s = pop_lsb(&b);
360       si->pawnKey ^= Zobrist::psq[piece_on(s)][s];
361   }
362
363   for (Piece pc : Pieces)
364   {
365       if (type_of(pc) != PAWN && type_of(pc) != KING)
366           si->nonPawnMaterial[color_of(pc)] += pieceCount[pc] * PieceValue[MG][pc];
367
368       for (int cnt = 0; cnt < pieceCount[pc]; ++cnt)
369           si->materialKey ^= Zobrist::psq[pc][cnt];
370   }
371 }
372
373
374 /// Position::set() is an overload to initialize the position object with
375 /// the given endgame code string like "KBPKN". It is manily an helper to
376 /// get the material key out of an endgame code. Position is not playable,
377 /// indeed is even not guaranteed to be legal.
378
379 Position& Position::set(const string& code, Color c, StateInfo* si) {
380
381   assert(code.length() > 0 && code.length() < 8);
382   assert(code[0] == 'K');
383
384   string sides[] = { code.substr(code.find('K', 1)),      // Weak
385                      code.substr(0, code.find('K', 1)) }; // Strong
386
387   std::transform(sides[c].begin(), sides[c].end(), sides[c].begin(), tolower);
388
389   string fenStr =  sides[0] + char(8 - sides[0].length() + '0') + "/8/8/8/8/8/8/"
390                  + sides[1] + char(8 - sides[1].length() + '0') + " w - - 0 10";
391
392   return set(fenStr, false, si, nullptr);
393 }
394
395
396 /// Position::fen() returns a FEN representation of the position. In case of
397 /// Chess960 the Shredder-FEN notation is used. This is mainly a debugging function.
398
399 const string Position::fen() const {
400
401   int emptyCnt;
402   std::ostringstream ss;
403
404   for (Rank r = RANK_8; r >= RANK_1; --r)
405   {
406       for (File f = FILE_A; f <= FILE_H; ++f)
407       {
408           for (emptyCnt = 0; f <= FILE_H && empty(make_square(f, r)); ++f)
409               ++emptyCnt;
410
411           if (emptyCnt)
412               ss << emptyCnt;
413
414           if (f <= FILE_H)
415               ss << PieceToChar[piece_on(make_square(f, r))];
416       }
417
418       if (r > RANK_1)
419           ss << '/';
420   }
421
422   ss << (sideToMove == WHITE ? " w " : " b ");
423
424   if (can_castle(WHITE_OO))
425       ss << (chess960 ? char('A' + file_of(castling_rook_square(WHITE |  KING_SIDE))) : 'K');
426
427   if (can_castle(WHITE_OOO))
428       ss << (chess960 ? char('A' + file_of(castling_rook_square(WHITE | QUEEN_SIDE))) : 'Q');
429
430   if (can_castle(BLACK_OO))
431       ss << (chess960 ? char('a' + file_of(castling_rook_square(BLACK |  KING_SIDE))) : 'k');
432
433   if (can_castle(BLACK_OOO))
434       ss << (chess960 ? char('a' + file_of(castling_rook_square(BLACK | QUEEN_SIDE))) : 'q');
435
436   if (!can_castle(WHITE) && !can_castle(BLACK))
437       ss << '-';
438
439   ss << (ep_square() == SQ_NONE ? " - " : " " + UCI::square(ep_square()) + " ")
440      << st->rule50 << " " << 1 + (gamePly - (sideToMove == BLACK)) / 2;
441
442   return ss.str();
443 }
444
445
446 /// Position::game_phase() calculates the game phase interpolating total non-pawn
447 /// material between endgame and midgame limits.
448
449 Phase Position::game_phase() const {
450
451   Value npm = st->nonPawnMaterial[WHITE] + st->nonPawnMaterial[BLACK];
452
453   npm = std::max(EndgameLimit, std::min(npm, MidgameLimit));
454
455   return Phase(((npm - EndgameLimit) * PHASE_MIDGAME) / (MidgameLimit - EndgameLimit));
456 }
457
458
459 /// Position::slider_blockers() returns a bitboard of all the pieces (both colors)
460 /// that are blocking attacks on the square 's' from 'sliders'. A piece blocks a
461 /// slider if removing that piece from the board would result in a position where
462 /// square 's' is attacked. For example, a king-attack blocking piece can be either
463 /// a pinned or a discovered check piece, according if its color is the opposite
464 /// or the same of the color of the slider.
465
466 Bitboard Position::slider_blockers(Bitboard sliders, Square s, Bitboard& pinners) const {
467
468   Bitboard result = 0;
469   pinners = 0;
470
471   // Snipers are sliders that attack 's' when a piece is removed
472   Bitboard snipers = (  (PseudoAttacks[ROOK  ][s] & pieces(QUEEN, ROOK))
473                       | (PseudoAttacks[BISHOP][s] & pieces(QUEEN, BISHOP))) & sliders;
474
475   while (snipers)
476   {
477     Square sniperSq = pop_lsb(&snipers);
478     Bitboard b = between_bb(s, sniperSq) & pieces();
479
480     if (!more_than_one(b))
481     {
482         result |= b;
483         if (b & pieces(color_of(piece_on(s))))
484             pinners |= sniperSq;
485     }
486   }
487   return result;
488 }
489
490
491 /// Position::attackers_to() computes a bitboard of all pieces which attack a
492 /// given square. Slider attacks use the occupied bitboard to indicate occupancy.
493
494 Bitboard Position::attackers_to(Square s, Bitboard occupied) const {
495
496   return  (attacks_from<PAWN>(s, BLACK)    & pieces(WHITE, PAWN))
497         | (attacks_from<PAWN>(s, WHITE)    & pieces(BLACK, PAWN))
498         | (attacks_from<KNIGHT>(s)         & pieces(KNIGHT))
499         | (attacks_bb<ROOK  >(s, occupied) & pieces(ROOK,   QUEEN))
500         | (attacks_bb<BISHOP>(s, occupied) & pieces(BISHOP, QUEEN))
501         | (attacks_from<KING>(s)           & pieces(KING));
502 }
503
504
505 /// Position::legal() tests whether a pseudo-legal move is legal
506
507 bool Position::legal(Move m) const {
508
509   assert(is_ok(m));
510
511   Color us = sideToMove;
512   Square from = from_sq(m);
513
514   assert(color_of(moved_piece(m)) == us);
515   assert(piece_on(square<KING>(us)) == make_piece(us, KING));
516
517   // En passant captures are a tricky special case. Because they are rather
518   // uncommon, we do it simply by testing whether the king is attacked after
519   // the move is made.
520   if (type_of(m) == ENPASSANT)
521   {
522       Square ksq = square<KING>(us);
523       Square to = to_sq(m);
524       Square capsq = to - pawn_push(us);
525       Bitboard occupied = (pieces() ^ from ^ capsq) | to;
526
527       assert(to == ep_square());
528       assert(moved_piece(m) == make_piece(us, PAWN));
529       assert(piece_on(capsq) == make_piece(~us, PAWN));
530       assert(piece_on(to) == NO_PIECE);
531
532       return   !(attacks_bb<  ROOK>(ksq, occupied) & pieces(~us, QUEEN, ROOK))
533             && !(attacks_bb<BISHOP>(ksq, occupied) & pieces(~us, QUEEN, BISHOP));
534   }
535
536   // If the moving piece is a king, check whether the destination
537   // square is attacked by the opponent. Castling moves are checked
538   // for legality during move generation.
539   if (type_of(piece_on(from)) == KING)
540       return type_of(m) == CASTLING || !(attackers_to(to_sq(m)) & pieces(~us));
541
542   // A non-king move is legal if and only if it is not pinned or it
543   // is moving along the ray towards or away from the king.
544   return   !(pinned_pieces(us) & from)
545         ||  aligned(from, to_sq(m), square<KING>(us));
546 }
547
548
549 /// Position::pseudo_legal() takes a random move and tests whether the move is
550 /// pseudo legal. It is used to validate moves from TT that can be corrupted
551 /// due to SMP concurrent access or hash position key aliasing.
552
553 bool Position::pseudo_legal(const Move m) const {
554
555   Color us = sideToMove;
556   Square from = from_sq(m);
557   Square to = to_sq(m);
558   Piece pc = moved_piece(m);
559
560   // Use a slower but simpler function for uncommon cases
561   if (type_of(m) != NORMAL)
562       return MoveList<LEGAL>(*this).contains(m);
563
564   // Is not a promotion, so promotion piece must be empty
565   if (promotion_type(m) - KNIGHT != NO_PIECE_TYPE)
566       return false;
567
568   // If the 'from' square is not occupied by a piece belonging to the side to
569   // move, the move is obviously not legal.
570   if (pc == NO_PIECE || color_of(pc) != us)
571       return false;
572
573   // The destination square cannot be occupied by a friendly piece
574   if (pieces(us) & to)
575       return false;
576
577   // Handle the special case of a pawn move
578   if (type_of(pc) == PAWN)
579   {
580       // We have already handled promotion moves, so destination
581       // cannot be on the 8th/1st rank.
582       if (rank_of(to) == relative_rank(us, RANK_8))
583           return false;
584
585       if (   !(attacks_from<PAWN>(from, us) & pieces(~us) & to) // Not a capture
586           && !((from + pawn_push(us) == to) && empty(to))       // Not a single push
587           && !(   (from + 2 * pawn_push(us) == to)              // Not a double push
588                && (rank_of(from) == relative_rank(us, RANK_2))
589                && empty(to)
590                && empty(to - pawn_push(us))))
591           return false;
592   }
593   else if (!(attacks_from(pc, from) & to))
594       return false;
595
596   // Evasions generator already takes care to avoid some kind of illegal moves
597   // and legal() relies on this. We therefore have to take care that the same
598   // kind of moves are filtered out here.
599   if (checkers())
600   {
601       if (type_of(pc) != KING)
602       {
603           // Double check? In this case a king move is required
604           if (more_than_one(checkers()))
605               return false;
606
607           // Our move must be a blocking evasion or a capture of the checking piece
608           if (!((between_bb(lsb(checkers()), square<KING>(us)) | checkers()) & to))
609               return false;
610       }
611       // In case of king moves under check we have to remove king so as to catch
612       // invalid moves like b1a1 when opposite queen is on c1.
613       else if (attackers_to(to, pieces() ^ from) & pieces(~us))
614           return false;
615   }
616
617   return true;
618 }
619
620
621 /// Position::gives_check() tests whether a pseudo-legal move gives a check
622
623 bool Position::gives_check(Move m) const {
624
625   assert(is_ok(m));
626   assert(color_of(moved_piece(m)) == sideToMove);
627
628   Square from = from_sq(m);
629   Square to = to_sq(m);
630
631   // Is there a direct check?
632   if (st->checkSquares[type_of(piece_on(from))] & to)
633       return true;
634
635   // Is there a discovered check?
636   if (   (discovered_check_candidates() & from)
637       && !aligned(from, to, square<KING>(~sideToMove)))
638       return true;
639
640   switch (type_of(m))
641   {
642   case NORMAL:
643       return false;
644
645   case PROMOTION:
646       return attacks_bb(Piece(promotion_type(m)), to, pieces() ^ from) & square<KING>(~sideToMove);
647
648   // En passant capture with check? We have already handled the case
649   // of direct checks and ordinary discovered check, so the only case we
650   // need to handle is the unusual case of a discovered check through
651   // the captured pawn.
652   case ENPASSANT:
653   {
654       Square capsq = make_square(file_of(to), rank_of(from));
655       Bitboard b = (pieces() ^ from ^ capsq) | to;
656
657       return  (attacks_bb<  ROOK>(square<KING>(~sideToMove), b) & pieces(sideToMove, QUEEN, ROOK))
658             | (attacks_bb<BISHOP>(square<KING>(~sideToMove), b) & pieces(sideToMove, QUEEN, BISHOP));
659   }
660   case CASTLING:
661   {
662       Square kfrom = from;
663       Square rfrom = to; // Castling is encoded as 'King captures the rook'
664       Square kto = relative_square(sideToMove, rfrom > kfrom ? SQ_G1 : SQ_C1);
665       Square rto = relative_square(sideToMove, rfrom > kfrom ? SQ_F1 : SQ_D1);
666
667       return   (PseudoAttacks[ROOK][rto] & square<KING>(~sideToMove))
668             && (attacks_bb<ROOK>(rto, (pieces() ^ kfrom ^ rfrom) | rto | kto) & square<KING>(~sideToMove));
669   }
670   default:
671       assert(false);
672       return false;
673   }
674 }
675
676
677 /// Position::do_move() makes a move, and saves all information necessary
678 /// to a StateInfo object. The move is assumed to be legal. Pseudo-legal
679 /// moves should be filtered out before this function is called.
680
681 void Position::do_move(Move m, StateInfo& newSt, bool givesCheck) {
682
683   assert(is_ok(m));
684   assert(&newSt != st);
685
686   ++nodes;
687   Key k = st->key ^ Zobrist::side;
688
689   // Copy some fields of the old state to our new StateInfo object except the
690   // ones which are going to be recalculated from scratch anyway and then switch
691   // our state pointer to point to the new (ready to be updated) state.
692   std::memcpy(&newSt, st, offsetof(StateInfo, key));
693   newSt.previous = st;
694   st = &newSt;
695
696   // Increment ply counters. In particular, rule50 will be reset to zero later on
697   // in case of a capture or a pawn move.
698   ++gamePly;
699   ++st->rule50;
700   ++st->pliesFromNull;
701
702   Color us = sideToMove;
703   Color them = ~us;
704   Square from = from_sq(m);
705   Square to = to_sq(m);
706   Piece pc = piece_on(from);
707   Piece captured = type_of(m) == ENPASSANT ? make_piece(them, PAWN) : piece_on(to);
708
709   assert(color_of(pc) == us);
710   assert(captured == NO_PIECE || color_of(captured) == (type_of(m) != CASTLING ? them : us));
711   assert(type_of(captured) != KING);
712
713   if (type_of(m) == CASTLING)
714   {
715       assert(pc == make_piece(us, KING));
716       assert(captured == make_piece(us, ROOK));
717
718       Square rfrom, rto;
719       do_castling<true>(us, from, to, rfrom, rto);
720
721       st->psq += PSQT::psq[captured][rto] - PSQT::psq[captured][rfrom];
722       k ^= Zobrist::psq[captured][rfrom] ^ Zobrist::psq[captured][rto];
723       captured = NO_PIECE;
724   }
725
726   if (captured)
727   {
728       Square capsq = to;
729
730       // If the captured piece is a pawn, update pawn hash key, otherwise
731       // update non-pawn material.
732       if (type_of(captured) == PAWN)
733       {
734           if (type_of(m) == ENPASSANT)
735           {
736               capsq -= pawn_push(us);
737
738               assert(pc == make_piece(us, PAWN));
739               assert(to == st->epSquare);
740               assert(relative_rank(us, to) == RANK_6);
741               assert(piece_on(to) == NO_PIECE);
742               assert(piece_on(capsq) == make_piece(them, PAWN));
743
744               board[capsq] = NO_PIECE; // Not done by remove_piece()
745           }
746
747           st->pawnKey ^= Zobrist::psq[captured][capsq];
748       }
749       else
750           st->nonPawnMaterial[them] -= PieceValue[MG][captured];
751
752       // Update board and piece lists
753       remove_piece(captured, capsq);
754
755       // Update material hash key and prefetch access to materialTable
756       k ^= Zobrist::psq[captured][capsq];
757       st->materialKey ^= Zobrist::psq[captured][pieceCount[captured]];
758       prefetch(thisThread->materialTable[st->materialKey]);
759
760       // Update incremental scores
761       st->psq -= PSQT::psq[captured][capsq];
762
763       // Reset rule 50 counter
764       st->rule50 = 0;
765   }
766
767   // Update hash key
768   k ^= Zobrist::psq[pc][from] ^ Zobrist::psq[pc][to];
769
770   // Reset en passant square
771   if (st->epSquare != SQ_NONE)
772   {
773       k ^= Zobrist::enpassant[file_of(st->epSquare)];
774       st->epSquare = SQ_NONE;
775   }
776
777   // Update castling rights if needed
778   if (st->castlingRights && (castlingRightsMask[from] | castlingRightsMask[to]))
779   {
780       int cr = castlingRightsMask[from] | castlingRightsMask[to];
781       k ^= Zobrist::castling[st->castlingRights & cr];
782       st->castlingRights &= ~cr;
783   }
784
785   // Move the piece. The tricky Chess960 castling is handled earlier
786   if (type_of(m) != CASTLING)
787       move_piece(pc, from, to);
788
789   // If the moving piece is a pawn do some special extra work
790   if (type_of(pc) == PAWN)
791   {
792       // Set en-passant square if the moved pawn can be captured
793       if (   (int(to) ^ int(from)) == 16
794           && (attacks_from<PAWN>(to - pawn_push(us), us) & pieces(them, PAWN)))
795       {
796           st->epSquare = (from + to) / 2;
797           k ^= Zobrist::enpassant[file_of(st->epSquare)];
798       }
799
800       else if (type_of(m) == PROMOTION)
801       {
802           Piece promotion = make_piece(us, promotion_type(m));
803
804           assert(relative_rank(us, to) == RANK_8);
805           assert(type_of(promotion) >= KNIGHT && type_of(promotion) <= QUEEN);
806
807           remove_piece(pc, to);
808           put_piece(promotion, to);
809
810           // Update hash keys
811           k ^= Zobrist::psq[pc][to] ^ Zobrist::psq[promotion][to];
812           st->pawnKey ^= Zobrist::psq[pc][to];
813           st->materialKey ^=  Zobrist::psq[promotion][pieceCount[promotion]-1]
814                             ^ Zobrist::psq[pc][pieceCount[pc]];
815
816           // Update incremental score
817           st->psq += PSQT::psq[promotion][to] - PSQT::psq[pc][to];
818
819           // Update material
820           st->nonPawnMaterial[us] += PieceValue[MG][promotion];
821       }
822
823       // Update pawn hash key and prefetch access to pawnsTable
824       st->pawnKey ^= Zobrist::psq[pc][from] ^ Zobrist::psq[pc][to];
825       prefetch(thisThread->pawnsTable[st->pawnKey]);
826
827       // Reset rule 50 draw counter
828       st->rule50 = 0;
829   }
830
831   // Update incremental scores
832   st->psq += PSQT::psq[pc][to] - PSQT::psq[pc][from];
833
834   // Set capture piece
835   st->capturedPiece = captured;
836
837   // Update the key with the final value
838   st->key = k;
839
840   // Calculate checkers bitboard (if move gives check)
841   st->checkersBB = givesCheck ? attackers_to(square<KING>(them)) & pieces(us) : 0;
842
843   sideToMove = ~sideToMove;
844
845   // Update king attacks used for fast check detection
846   set_check_info(st);
847
848   assert(pos_is_ok());
849 }
850
851
852 /// Position::undo_move() unmakes a move. When it returns, the position should
853 /// be restored to exactly the same state as before the move was made.
854
855 void Position::undo_move(Move m) {
856
857   assert(is_ok(m));
858
859   sideToMove = ~sideToMove;
860
861   Color us = sideToMove;
862   Square from = from_sq(m);
863   Square to = to_sq(m);
864   Piece pc = piece_on(to);
865
866   assert(empty(from) || type_of(m) == CASTLING);
867   assert(type_of(st->capturedPiece) != KING);
868
869   if (type_of(m) == PROMOTION)
870   {
871       assert(relative_rank(us, to) == RANK_8);
872       assert(type_of(pc) == promotion_type(m));
873       assert(type_of(pc) >= KNIGHT && type_of(pc) <= QUEEN);
874
875       remove_piece(pc, to);
876       pc = make_piece(us, PAWN);
877       put_piece(pc, to);
878   }
879
880   if (type_of(m) == CASTLING)
881   {
882       Square rfrom, rto;
883       do_castling<false>(us, from, to, rfrom, rto);
884   }
885   else
886   {
887       move_piece(pc, to, from); // Put the piece back at the source square
888
889       if (st->capturedPiece)
890       {
891           Square capsq = to;
892
893           if (type_of(m) == ENPASSANT)
894           {
895               capsq -= pawn_push(us);
896
897               assert(type_of(pc) == PAWN);
898               assert(to == st->previous->epSquare);
899               assert(relative_rank(us, to) == RANK_6);
900               assert(piece_on(capsq) == NO_PIECE);
901               assert(st->capturedPiece == make_piece(~us, PAWN));
902           }
903
904           put_piece(st->capturedPiece, capsq); // Restore the captured piece
905       }
906   }
907
908   // Finally point our state pointer back to the previous state
909   st = st->previous;
910   --gamePly;
911
912   assert(pos_is_ok());
913 }
914
915
916 /// Position::do_castling() is a helper used to do/undo a castling move. This
917 /// is a bit tricky in Chess960 where from/to squares can overlap.
918 template<bool Do>
919 void Position::do_castling(Color us, Square from, Square& to, Square& rfrom, Square& rto) {
920
921   bool kingSide = to > from;
922   rfrom = to; // Castling is encoded as "king captures friendly rook"
923   rto = relative_square(us, kingSide ? SQ_F1 : SQ_D1);
924   to = relative_square(us, kingSide ? SQ_G1 : SQ_C1);
925
926   // Remove both pieces first since squares could overlap in Chess960
927   remove_piece(make_piece(us, KING), Do ? from : to);
928   remove_piece(make_piece(us, ROOK), Do ? rfrom : rto);
929   board[Do ? from : to] = board[Do ? rfrom : rto] = NO_PIECE; // Since remove_piece doesn't do it for us
930   put_piece(make_piece(us, KING), Do ? to : from);
931   put_piece(make_piece(us, ROOK), Do ? rto : rfrom);
932 }
933
934
935 /// Position::do(undo)_null_move() is used to do(undo) a "null move": It flips
936 /// the side to move without executing any move on the board.
937
938 void Position::do_null_move(StateInfo& newSt) {
939
940   assert(!checkers());
941   assert(&newSt != st);
942
943   std::memcpy(&newSt, st, sizeof(StateInfo));
944   newSt.previous = st;
945   st = &newSt;
946
947   if (st->epSquare != SQ_NONE)
948   {
949       st->key ^= Zobrist::enpassant[file_of(st->epSquare)];
950       st->epSquare = SQ_NONE;
951   }
952
953   st->key ^= Zobrist::side;
954   prefetch(TT.first_entry(st->key));
955
956   ++st->rule50;
957   st->pliesFromNull = 0;
958
959   sideToMove = ~sideToMove;
960
961   set_check_info(st);
962
963   assert(pos_is_ok());
964 }
965
966 void Position::undo_null_move() {
967
968   assert(!checkers());
969
970   st = st->previous;
971   sideToMove = ~sideToMove;
972 }
973
974
975 /// Position::key_after() computes the new hash key after the given move. Needed
976 /// for speculative prefetch. It doesn't recognize special moves like castling,
977 /// en-passant and promotions.
978
979 Key Position::key_after(Move m) const {
980
981   Square from = from_sq(m);
982   Square to = to_sq(m);
983   Piece pc = piece_on(from);
984   Piece captured = piece_on(to);
985   Key k = st->key ^ Zobrist::side;
986
987   if (captured)
988       k ^= Zobrist::psq[captured][to];
989
990   return k ^ Zobrist::psq[pc][to] ^ Zobrist::psq[pc][from];
991 }
992
993
994 /// Position::see_ge (Static Exchange Evaluation Greater or Equal) tests if the
995 /// SEE value of move is greater or equal to the given value. We'll use an
996 /// algorithm similar to alpha-beta pruning with a null window.
997
998 bool Position::see_ge(Move m, Value v) const {
999
1000   assert(is_ok(m));
1001
1002   // Castling moves are implemented as king capturing the rook so cannot be
1003   // handled correctly. Simply assume the SEE value is VALUE_ZERO that is always
1004   // correct unless in the rare case the rook ends up under attack.
1005   if (type_of(m) == CASTLING)
1006       return VALUE_ZERO >= v;
1007
1008   Square from = from_sq(m), to = to_sq(m);
1009   PieceType nextVictim = type_of(piece_on(from));
1010   Color stm = ~color_of(piece_on(from)); // First consider opponent's move
1011   Value balance; // Values of the pieces taken by us minus opponent's ones
1012   Bitboard occupied, stmAttackers;
1013
1014   if (type_of(m) == ENPASSANT)
1015   {
1016       occupied = SquareBB[to - pawn_push(~stm)]; // Remove the captured pawn
1017       balance = PieceValue[MG][PAWN];
1018   }
1019   else
1020   {
1021       balance = PieceValue[MG][piece_on(to)];
1022       occupied = 0;
1023   }
1024
1025   if (balance < v)
1026       return false;
1027
1028   if (nextVictim == KING)
1029       return true;
1030
1031   balance -= PieceValue[MG][nextVictim];
1032
1033   if (balance >= v)
1034       return true;
1035
1036   bool relativeStm = true; // True if the opponent is to move
1037   occupied ^= pieces() ^ from ^ to;
1038
1039   // Find all attackers to the destination square, with the moving piece removed,
1040   // but possibly an X-ray attacker added behind it.
1041   Bitboard attackers = attackers_to(to, occupied) & occupied;
1042
1043   while (true)
1044   {
1045       stmAttackers = attackers & pieces(stm);
1046
1047       // Don't allow pinned pieces to attack pieces except the king as long all
1048       // pinners are on their original square.
1049       if (!(st->pinnersForKing[stm] & ~occupied))
1050           stmAttackers &= ~st->blockersForKing[stm];
1051
1052       if (!stmAttackers)
1053           return relativeStm;
1054
1055       // Locate and remove the next least valuable attacker
1056       nextVictim = min_attacker<PAWN>(byTypeBB, to, stmAttackers, occupied, attackers);
1057
1058       if (nextVictim == KING)
1059           return relativeStm == bool(attackers & pieces(~stm));
1060
1061       balance += relativeStm ?  PieceValue[MG][nextVictim]
1062                              : -PieceValue[MG][nextVictim];
1063
1064       relativeStm = !relativeStm;
1065
1066       if (relativeStm == (balance >= v))
1067           return relativeStm;
1068
1069       stm = ~stm;
1070   }
1071 }
1072
1073
1074 /// Position::is_draw() tests whether the position is drawn by 50-move rule
1075 /// or by repetition. It does not detect stalemates.
1076
1077 bool Position::is_draw() const {
1078
1079   if (st->rule50 > 99 && (!checkers() || MoveList<LEGAL>(*this).size()))
1080       return true;
1081
1082   StateInfo* stp = st;
1083   for (int i = 2, e = std::min(st->rule50, st->pliesFromNull); i <= e; i += 2)
1084   {
1085       stp = stp->previous->previous;
1086
1087       if (stp->key == st->key)
1088           return true; // Draw at first repetition
1089   }
1090
1091   return false;
1092 }
1093
1094
1095 /// Position::flip() flips position with the white and black sides reversed. This
1096 /// is only useful for debugging e.g. for finding evaluation symmetry bugs.
1097
1098 void Position::flip() {
1099
1100   string f, token;
1101   std::stringstream ss(fen());
1102
1103   for (Rank r = RANK_8; r >= RANK_1; --r) // Piece placement
1104   {
1105       std::getline(ss, token, r > RANK_1 ? '/' : ' ');
1106       f.insert(0, token + (f.empty() ? " " : "/"));
1107   }
1108
1109   ss >> token; // Active color
1110   f += (token == "w" ? "B " : "W "); // Will be lowercased later
1111
1112   ss >> token; // Castling availability
1113   f += token + " ";
1114
1115   std::transform(f.begin(), f.end(), f.begin(),
1116                  [](char c) { return char(islower(c) ? toupper(c) : tolower(c)); });
1117
1118   ss >> token; // En passant square
1119   f += (token == "-" ? token : token.replace(1, 1, token[1] == '3' ? "6" : "3"));
1120
1121   std::getline(ss, token); // Half and full moves
1122   f += token;
1123
1124   set(f, is_chess960(), st, this_thread());
1125
1126   assert(pos_is_ok());
1127 }
1128
1129
1130 /// Position::pos_is_ok() performs some consistency checks for the position object.
1131 /// This is meant to be helpful when debugging.
1132
1133 bool Position::pos_is_ok(int* failedStep) const {
1134
1135   const bool Fast = true; // Quick (default) or full check?
1136
1137   enum { Default, King, Bitboards, State, Lists, Castling };
1138
1139   for (int step = Default; step <= (Fast ? Default : Castling); step++)
1140   {
1141       if (failedStep)
1142           *failedStep = step;
1143
1144       if (step == Default)
1145           if (   (sideToMove != WHITE && sideToMove != BLACK)
1146               || piece_on(square<KING>(WHITE)) != W_KING
1147               || piece_on(square<KING>(BLACK)) != B_KING
1148               || (   ep_square() != SQ_NONE
1149                   && relative_rank(sideToMove, ep_square()) != RANK_6))
1150               return false;
1151
1152       if (step == King)
1153           if (   std::count(board, board + SQUARE_NB, W_KING) != 1
1154               || std::count(board, board + SQUARE_NB, B_KING) != 1
1155               || attackers_to(square<KING>(~sideToMove)) & pieces(sideToMove))
1156               return false;
1157
1158       if (step == Bitboards)
1159       {
1160           if (  (pieces(WHITE) & pieces(BLACK))
1161               ||(pieces(WHITE) | pieces(BLACK)) != pieces())
1162               return false;
1163
1164           for (PieceType p1 = PAWN; p1 <= KING; ++p1)
1165               for (PieceType p2 = PAWN; p2 <= KING; ++p2)
1166                   if (p1 != p2 && (pieces(p1) & pieces(p2)))
1167                       return false;
1168       }
1169
1170       if (step == State)
1171       {
1172           StateInfo si = *st;
1173           set_state(&si);
1174           if (std::memcmp(&si, st, sizeof(StateInfo)))
1175               return false;
1176       }
1177
1178       if (step == Lists)
1179           for (Piece pc : Pieces)
1180           {
1181               if (pieceCount[pc] != popcount(pieces(color_of(pc), type_of(pc))))
1182                   return false;
1183
1184               for (int i = 0; i < pieceCount[pc]; ++i)
1185                   if (board[pieceList[pc][i]] != pc || index[pieceList[pc][i]] != i)
1186                       return false;
1187           }
1188
1189       if (step == Castling)
1190           for (Color c = WHITE; c <= BLACK; ++c)
1191               for (CastlingSide s = KING_SIDE; s <= QUEEN_SIDE; s = CastlingSide(s + 1))
1192               {
1193                   if (!can_castle(c | s))
1194                       continue;
1195
1196                   if (   piece_on(castlingRookSquare[c | s]) != make_piece(c, ROOK)
1197                       || castlingRightsMask[castlingRookSquare[c | s]] != (c | s)
1198                       ||(castlingRightsMask[square<KING>(c)] & (c | s)) != (c | s))
1199                       return false;
1200               }
1201   }
1202
1203   return true;
1204 }