Skip to content

Commit

Permalink
read_game: don't pop/end_variation while skipping
Browse files Browse the repository at this point in the history
If the Visitor class enters a variation without skipping, then returns
SKIP for a variation nested inside it, the traversal state is messed up
when the inside variation ends.  If our skip depth is anything greater
than zero when we reach a ')' token, we should not visit the end of a
variation or pop the board_stack, because it is being skipped
completely.

Short testcase:

    import chess, chess.pgn as pgn, io

    class MainlineW(pgn.GameBuilder):
        """Includes variations played by Black but not by White"""
        def begin_variation(self):
            if self.variation_stack[-1].turn() != chess.WHITE:
                return pgn.SKIP
            return super().begin_variation()

    g = pgn.read_game(io.StringIO(
            '1. e4 e5 (1... d5 2.exd5 Qxd5 3. Nc3 (3. c4) 3... Qa5)'),
        Visitor=MainlineW)
  • Loading branch information
djpohly committed Jul 23, 2021
1 parent 57eecae commit 17e5c8d
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion chess/pgn.py
Original file line number Diff line number Diff line change
Expand Up @@ -1599,7 +1599,7 @@ def read_game(handle: TextIO, *, Visitor: Any = GameBuilder) -> Any:
elif token == ")":
if skip_variation_depth:
skip_variation_depth -= 1
if len(board_stack) > 1:
elif len(board_stack) > 1:
visitor.end_variation()
board_stack.pop()
elif skip_variation_depth:
Expand Down

0 comments on commit 17e5c8d

Please sign in to comment.