Skip to main content

ferrichess_study/
domain.rs

1use std::path::{Path, PathBuf};
2
3use serde::{Deserialize, Serialize};
4use shakmaty::{Bitboard, Board, Color, EnPassantMode, Position, Square};
5
6/// The side for which repertoire moves are selected.
7#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
8pub enum RepertoireSide {
9    White,
10    Black,
11}
12
13impl RepertoireSide {
14    #[must_use]
15    pub const fn color(self) -> Color {
16        match self {
17            Self::White => Color::White,
18            Self::Black => Color::Black,
19        }
20    }
21
22    #[must_use]
23    pub fn is_repertoire_turn(self, turn: Color) -> bool {
24        self.color() == turn
25    }
26}
27
28impl From<RepertoireSide> for Color {
29    fn from(side: RepertoireSide) -> Self {
30        side.color()
31    }
32}
33
34/// Whether a chapter is a primary repertoire chapter or a variant chapter.
35#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
36pub enum RepertoireRole {
37    Main,
38    Variant,
39}
40
41/// A human-readable move annotation or position evaluation.
42#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
43pub enum Annotation {
44    Good,
45    Mistake,
46    Brilliant,
47    Blunder,
48    Interesting,
49    Dubious,
50    Equal,
51    Unclear,
52    EqualWithCounterplay,
53    WhiteSlightAdvantage,
54    BlackSlightAdvantage,
55    WhiteAdvantage,
56    BlackAdvantage,
57    WhiteWinning,
58    BlackWinning,
59    Counterplay,
60}
61
62impl Annotation {
63    /// Returns the standard PGN numeric annotation glyph for a position
64    /// evaluation. Move-quality annotations retain their SAN suffixes.
65    #[must_use]
66    pub const fn evaluation_nag(self) -> Option<u16> {
67        match self {
68            Self::Equal => Some(10),
69            Self::EqualWithCounterplay => Some(12),
70            Self::Unclear => Some(13),
71            Self::WhiteSlightAdvantage => Some(14),
72            Self::BlackSlightAdvantage => Some(15),
73            Self::WhiteAdvantage => Some(16),
74            Self::BlackAdvantage => Some(17),
75            Self::WhiteWinning => Some(18),
76            Self::BlackWinning => Some(19),
77            Self::Counterplay => Some(132),
78            Self::Good
79            | Self::Mistake
80            | Self::Brilliant
81            | Self::Blunder
82            | Self::Interesting
83            | Self::Dubious => None,
84        }
85    }
86
87    #[must_use]
88    pub const fn suffix(self) -> &'static str {
89        match self {
90            Self::Good => "!",
91            Self::Mistake => "?",
92            Self::Brilliant => "!!",
93            Self::Blunder => "??",
94            Self::Interesting => "!?",
95            Self::Dubious => "?!",
96            Self::Equal => "=",
97            Self::Unclear => "∞",
98            Self::EqualWithCounterplay => "=∞",
99            Self::WhiteSlightAdvantage => "⩲",
100            Self::BlackSlightAdvantage => "⩱",
101            Self::WhiteAdvantage => "±",
102            Self::BlackAdvantage => "∓",
103            Self::WhiteWinning => "+–",
104            Self::BlackWinning => "–+",
105            Self::Counterplay => "⇆",
106        }
107    }
108
109    /// Returns an ASCII spelling suitable for normalized raw/comment text.
110    #[must_use]
111    pub const fn ascii_suffix(self) -> &'static str {
112        match self {
113            Self::Good => "!",
114            Self::Mistake => "?",
115            Self::Brilliant => "!!",
116            Self::Blunder => "??",
117            Self::Interesting => "!?",
118            Self::Dubious => "?!",
119            Self::Equal => "=",
120            Self::Unclear => "~",
121            Self::EqualWithCounterplay => "=~",
122            Self::WhiteSlightAdvantage => "+=",
123            Self::BlackSlightAdvantage => "=+",
124            Self::WhiteAdvantage => "+/-",
125            Self::BlackAdvantage => "-/+",
126            Self::WhiteWinning => "+-",
127            Self::BlackWinning => "-+",
128            Self::Counterplay => "<=>",
129        }
130    }
131
132    #[must_use]
133    pub fn from_suffix(suffix: &str) -> Option<Self> {
134        match suffix {
135            "!" => Some(Self::Good),
136            "?" => Some(Self::Mistake),
137            "!!" => Some(Self::Brilliant),
138            "??" => Some(Self::Blunder),
139            "!?" => Some(Self::Interesting),
140            "?!" => Some(Self::Dubious),
141            "=" => Some(Self::Equal),
142            "∞" | "~" => Some(Self::Unclear),
143            "=∞" | "=~" => Some(Self::EqualWithCounterplay),
144            "⩲" | "+=" => Some(Self::WhiteSlightAdvantage),
145            "⩱" | "=+" => Some(Self::BlackSlightAdvantage),
146            "±" | "+/-" => Some(Self::WhiteAdvantage),
147            "∓" | "-/+" => Some(Self::BlackAdvantage),
148            "+–" | "+-" => Some(Self::WhiteWinning),
149            "–+" | "-+" => Some(Self::BlackWinning),
150            "⇆" | "<=>" => Some(Self::Counterplay),
151            _ => None,
152        }
153    }
154}
155
156/// A limit measured in moves made by the repertoire side.
157#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
158pub enum DepthLimit {
159    #[default]
160    Unlimited,
161    RepertoireMoves(u32),
162}
163
164impl DepthLimit {
165    #[must_use]
166    pub const fn includes(self, repertoire_moves: u32) -> bool {
167        match self {
168            Self::Unlimited => true,
169            Self::RepertoireMoves(limit) => repertoire_moves <= limit,
170        }
171    }
172}
173
174/// Stable identity of an input source.
175#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
176pub struct SourceId(PathBuf);
177
178impl SourceId {
179    pub fn new(path: impl Into<PathBuf>) -> Self {
180        Self(path.into())
181    }
182
183    #[must_use]
184    pub fn as_path(&self) -> &Path {
185        &self.0
186    }
187
188    pub fn into_path_buf(self) -> PathBuf {
189        self.0
190    }
191}
192
193impl<T: Into<PathBuf>> From<T> for SourceId {
194    fn from(path: T) -> Self {
195        Self::new(path)
196    }
197}
198
199/// The first four FEN fields, with en passant normalized to legal captures.
200///
201/// Move clocks are deliberately excluded because they do not identify a
202/// repertoire position.
203#[derive(Clone, Debug, Eq, Hash, PartialEq)]
204pub struct PositionKey {
205    board: Board,
206    turn: Color,
207    castling_rights: Bitboard,
208    ep_square: Option<Square>,
209}
210
211impl PositionKey {
212    #[must_use]
213    pub fn from_position(position: &impl Position) -> Self {
214        Self {
215            board: position.board().clone(),
216            turn: position.turn(),
217            castling_rights: position.castles().castling_rights(),
218            ep_square: position.ep_square(EnPassantMode::Legal),
219        }
220    }
221
222    #[must_use]
223    pub const fn board(&self) -> &Board {
224        &self.board
225    }
226
227    #[must_use]
228    pub const fn turn(&self) -> Color {
229        self.turn
230    }
231
232    #[must_use]
233    pub const fn castling_rights(&self) -> Bitboard {
234        self.castling_rights
235    }
236
237    #[must_use]
238    pub const fn ep_square(&self) -> Option<Square> {
239        self.ep_square
240    }
241}
242
243#[cfg(test)]
244mod tests {
245    use shakmaty::{Chess, Move, Position, Role, Square};
246
247    use super::{Annotation, DepthLimit, PositionKey};
248
249    #[test]
250    fn annotations_have_readable_suffixes() {
251        assert_eq!(Annotation::Good.suffix(), "!");
252        assert_eq!(Annotation::Dubious.suffix(), "?!");
253        assert_eq!(Annotation::Blunder.suffix(), "??");
254        assert_eq!(Annotation::Counterplay.suffix(), "⇆");
255        assert_eq!(Annotation::WhiteWinning.suffix(), "+–");
256        assert_eq!(Annotation::WhiteWinning.evaluation_nag(), Some(18));
257        assert_eq!(Annotation::BlackWinning.evaluation_nag(), Some(19));
258        assert_eq!(Annotation::EqualWithCounterplay.evaluation_nag(), Some(12));
259        assert_eq!(Annotation::Good.evaluation_nag(), None);
260        assert_eq!(Annotation::WhiteWinning.ascii_suffix(), "+-");
261        assert_eq!(
262            Annotation::from_suffix("+-"),
263            Some(Annotation::WhiteWinning)
264        );
265    }
266
267    #[test]
268    fn depth_limit_counts_repertoire_moves_inclusively() {
269        assert!(DepthLimit::Unlimited.includes(u32::MAX));
270        assert!(DepthLimit::RepertoireMoves(2).includes(2));
271        assert!(!DepthLimit::RepertoireMoves(2).includes(3));
272    }
273
274    #[test]
275    fn position_key_uses_only_legal_en_passant_squares() {
276        let initial = Chess::default();
277        let after_e4 = initial
278            .play(Move::Normal {
279                role: Role::Pawn,
280                from: Square::E2,
281                capture: None,
282                to: Square::E4,
283                promotion: None,
284            })
285            .expect("e4 is legal in the initial position");
286
287        let key = PositionKey::from_position(&after_e4);
288        assert_eq!(key.turn(), shakmaty::Color::Black);
289        assert_eq!(key.ep_square(), None);
290    }
291}