aboutsummaryrefslogtreecommitdiff
path: root/cli/src/main.rs
blob: 5a7fd9698d9dee8c38ac9ac8042aef2c7e3b7ab9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
use serde::Deserialize;
use serde_json::Result;
use std::env;
use std::io::{BufRead, BufReader, Write};
use std::process::{ChildStdin, ChildStdout, Command, Stdio};
use std::string::String;

pub struct ChessEngine {
    stdin: ChildStdin,
    reader: BufReader<ChildStdout>,
}

#[derive(Deserialize)]
struct PerftResult {
    ms: i32,
    result: u64,
}
#[derive(Debug)]
pub struct PerftTest {
    pub position: &'static str,
    pub depth: i32,
    pub expected: u64,
}

pub struct HashTest {
    pub position: &'static str,
    pub moves: &'static str,
    pub hash: u64,
}

pub const PERFT_TESTS: &[PerftTest; 17] = &[
    PerftTest {
        position: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
        depth: 1,
        expected: 20,
    },
    PerftTest {
        position: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
        depth: 2,
        expected: 400,
    },
    PerftTest {
        position: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
        depth: 3,
        expected: 8902,
    },
    PerftTest {
        position: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
        depth: 4,
        expected: 197281,
    },
    PerftTest {
        position: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
        depth: 5,
        expected: 4865609,
    },
    // kiwipete
    PerftTest {
        position: "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1",
        depth: 1,
        expected: 48,
    },
    PerftTest {
        position: "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1",
        depth: 2,
        expected: 2039,
    },
    PerftTest {
        position: "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1",
        depth: 3,
        expected: 97862,
    },
    PerftTest {
        position: "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1",
        depth: 4,
        expected: 4085603,
    },
    // other ones
    PerftTest {
        position: "8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1",
        depth: 1,
        expected: 14,
    },
    PerftTest {
        position: "8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1",
        depth: 2,
        expected: 191,
    },
    PerftTest {
        position: "8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1",
        depth: 3,
        expected: 2812,
    },
    PerftTest {
        position: "8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1",
        depth: 4,
        expected: 43238,
    },
    // other position
    PerftTest {
        position: "r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq - 0 1",
        depth: 1,
        expected: 6,
    },
    PerftTest {
        position: "r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq - 0 1",
        depth: 2,
        expected: 264,
    },
    PerftTest {
        position: "r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq - 0 1",
        depth: 3,
        expected: 9467,
    },
    PerftTest {
        position: "r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq - 0 1",
        depth: 4,
        expected: 422333,
    },
];
pub const HASH_TESTS: &[HashTest; 12] = &[
    HashTest {
        position: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
        moves: "",
        hash: 5060803636482931868,
    },
    // one moves
    HashTest {
        position: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
        moves: "d2d4",
        hash: 9443689642921087454,
    },
    HashTest {
        position: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
        moves: "e2e4",
        hash: 9384546495678726550,
    },
    HashTest {
        position: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
        moves: "c2c4",
        hash: 14562399549841627035,
    },
    // two moves
    HashTest {
        position: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
        moves: "e2e4 e7e5",
        hash: 595762792459712928,
    },
    HashTest {
        position: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
        moves: "e2e4 c7c5",
        hash: 7227515431820872427,
    },
    HashTest {
        position: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
        moves: "e2e4 e7e6",
        hash: 17603279437685838276,
    },
    HashTest {
        position: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
        moves: "e2e4 c7c6",
        hash: 1172755318016414253,
    },
    HashTest {
        position: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
        moves: "d2d4 d7d5",
        hash: 460664201775194104,
    },
    // three moves
    HashTest {
        position: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
        moves: "e2e4 e7e5 g1f3",
        hash: 15213300192948443293,
    },
    HashTest {
        position: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
        moves: "d2d4 d7d5 c2c4",
        hash: 9963937660605248767,
    },
    // kiwipete
    HashTest {
        position: "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1",
        moves: "",
        hash: 14109232545397825053,
    },
];

impl ChessEngine {
    /// Spawns the engine process and initializes UCI mode
    pub fn new(path_to_engine: &str) -> Self {
        let mut child = Command::new(path_to_engine)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .expect("Failed to start chess engine");

        let stdin = child.stdin.take().expect("Failed to open stdin");
        let stdout = child.stdout.take().expect("Failed to open stdout");
        let reader = BufReader::new(stdout);

        let mut engine = Self { stdin, reader };

        // Boot up UCI mode
        engine.send_command("uci");
        engine.wait_for_response("uciok");

        engine
    }

    /// Sends a clean string command to the engine.
    /// Explicitly appends a newline and flushes the stream.
    pub fn send_command(&mut self, cmd: &str) {
        let formatted = format!("{}\n", cmd);
        self.stdin
            .write_all(formatted.as_bytes())
            .expect("Failed to write to engine");

        self.stdin.flush().expect("Failed to flush stdin");
    }

    /// Blocks and reads lines until a specific keyword signature is found
    pub fn wait_for_response(&mut self, expected_keyword: &str) -> Vec<String> {
        let mut lines = Vec::new();
        let mut line = String::new();

        while self.reader.read_line(&mut line).is_ok() {
            let clean_line = line.trim().to_string();
            if clean_line.starts_with("info") {
                println!("{}", clean_line)
            }
            lines.push(clean_line.clone());

            // Clear buffer for the next read loop
            line.clear();

            if clean_line.contains(expected_keyword) {
                break;
            }
        }
        lines
    }
    pub fn read_line(&mut self) -> String {
        let mut line = String::new();

        let _ = self.reader.read_line(&mut line);

        let clean_line = line.trim().to_string();
        if clean_line.starts_with("info") {
            println!("{}", clean_line)
        }
        clean_line
    }
}

fn test_perft(test: &PerftTest, engine: &mut ChessEngine) {
    let cmd = "position fen ".to_string() + &test.position;
    engine.send_command(&cmd);

    let cmd = "perft ".to_string() + &test.depth.to_string();
    engine.send_command(&cmd);
    let raw = engine.read_line();
    let result: Result<PerftResult> = serde_json::from_str(&raw);
    match result {
        Err(err) => {
            println!("error: {}", err);
        }
        Ok(perft) => {
            if perft.result == test.expected {
                println!(
                    "passed (Depth {}): {} nodes in {}ms",
                    test.depth, perft.result, perft.ms
                );
            } else {
                println!(
                    "FAILED Depth: {}, Expected: {}, got: {}, position: {}",
                    test.depth, test.expected, perft.result, test.position,
                );
                std::process::exit(1);
            }
        }
    }
}

fn test_hash(test: &HashTest, engine: &mut ChessEngine) {
    let cmd = "position fen ".to_string() + &test.position + " moves " + &test.moves;
    engine.send_command(&cmd);

    engine.send_command("hash");
    let line = engine.read_line();
    let hash: u64 = match line.trim().parse() {
        Ok(num) => num,
        Err(_) => {
            println!("Failed to parse hash: {}", line);
            std::process::exit(1)
        }
    };
    if hash == test.hash {
        println!(
            "passed {}: position: {}, moves: {}",
            hash, test.position, test.moves
        );
    } else {
        println!("FAILED position: {}, moves: {}", test.position, test.moves);
        std::process::exit(1);
    }
}

fn main() {
    let args: Vec<String> = env::args().collect();

    if args.len() != 2 {
        println!("usage: ./cli <path to test executable>");
        return;
    }

    let engine_path = &args[1];
    let mut engine = ChessEngine::new(engine_path);

    println!("Engine running");

    engine.send_command("isready");
    engine.wait_for_response("readyok");

    for test in HASH_TESTS.iter() {
        test_hash(&test, &mut engine);
    }
    for test in PERFT_TESTS.iter() {
        test_perft(test, &mut engine);
    }
}