]> git.sesse.net Git - stockfish/blob - src/uci.cpp
Use a string stream in UCIInputParser
[stockfish] / src / uci.cpp
1 /*
2   Glaurung, a UCI chess playing engine.
3   Copyright (C) 2004-2008 Tord Romstad
4
5   Glaurung is free software: you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation, either version 3 of the License, or
8   (at your option) any later version.
9   
10   Glaurung is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14   
15   You should have received a copy of the GNU General Public License
16   along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19
20 ////
21 //// Includes
22 ////
23
24 #include <iostream>
25 #include <sstream>
26 #include <string>
27
28 #include "book.h"
29 #include "evaluate.h"
30 #include "misc.h"
31 #include "move.h"
32 #include "movegen.h"
33 #include "position.h"
34 #include "san.h"
35 #include "search.h"
36 #include "uci.h"
37 #include "ucioption.h"
38
39
40 ////
41 //// Local definitions:
42 ////
43
44 namespace {
45
46   // UCIInputParser is a class for parsing UCI input.  The class is
47   // very simple, and basically just consist of a string stream
48   // built on a given input string.  There are methods for checking
49   // if we are at the end of the line, for getting the next token
50   // (defined as any whitespace-delimited sequence of characters),
51   // and for getting the rest of the line as a single string.
52
53   class UCIInputParser {
54
55   public:
56     UCIInputParser(const std::string &line);
57     std::string get_next_token();
58     std::string get_rest_of_line();
59     bool at_end_of_line();
60
61   private:
62     std::istringstream inputLineStream;
63
64   };
65
66
67   // The root position.  This is set up when the user (or in practice, the GUI)
68   // sends the "position" UCI command.  The root position is sent to the think()
69   // function when the program receives the "go" command.
70   Position RootPosition;
71
72   // Local functions
73   void wait_for_command();
74   void handle_command(const std::string &command);
75   void set_option(UCIInputParser &uip);
76   void set_position(UCIInputParser &uip);
77   void go(UCIInputParser &uip);
78 }
79
80
81 ////
82 //// Functions
83 ////
84
85 /// uci_main_loop() is the only global function in this file.  It is
86 /// called immediately after the program has finished initializing.
87 /// The program remains in this loop until it receives the "quit" UCI
88 /// command.
89
90 void uci_main_loop() {
91   RootPosition.from_fen(StartPosition);
92   while(1) wait_for_command();
93 }
94
95
96 ////
97 //// Local functions
98 ////
99
100 namespace {
101
102   ///
103   /// Implementation of the UCIInputParser class.
104   ///
105
106   // Constructor for the UCIInputParser class.  The constructor takes a 
107   // text string containing a single UCI command as input.
108
109   UCIInputParser::UCIInputParser(const std::string &line) : inputLineStream(line) { }
110
111
112   // UCIInputParser::get_next_token() gets the next token in an UCI
113   // command.  A 'token' in an UCI command is simply any
114   // whitespace-delimited sequence of characters.
115
116   std::string UCIInputParser::get_next_token() {
117
118     std::string token;
119
120     inputLineStream >> token; // operator >> skips any whitespace
121
122     return token;
123   }
124
125
126   // UCIInputParser::get_rest_of_line() returns the rest of the input
127   // line (from the current location) as a single string.
128
129   std::string UCIInputParser::get_rest_of_line() {
130
131     std::string tail;
132
133     std::getline(inputLineStream, tail);
134
135     return tail;
136   }
137
138
139   // UCIInputParser::at_end_of_line() tests whether we have reached the
140   // end of the input string, i.e. if any more input remains to be
141   // parsed.
142
143   bool UCIInputParser::at_end_of_line() {
144
145     return inputLineStream.eof();
146   }
147
148
149   /// 
150   /// Other functions
151   ///
152
153
154   // wait_for_command() waits for a command from the user, and passes
155   // this command to handle_command.  wait_for_command also intercepts
156   // EOF from stdin, by translating EOF to the "quit" command.  This
157   // ensures that Glaurung exits gracefully if the GUI dies
158   // unexpectedly.
159
160   void wait_for_command() {
161
162     std::string command;
163
164     if (!std::getline(std::cin, command))
165         command = "quit";
166
167     handle_command(command);
168   }
169
170
171   // handle_command() takes a text string as input, uses a
172   // UCIInputParser object to parse this text string as a UCI command,
173   // and calls the appropriate functions.  In addition to the UCI
174   // commands, the function also supports a few debug commands.
175   
176   void handle_command(const std::string &command) {
177
178     UCIInputParser uip(command);
179     std::string token = uip.get_next_token();
180
181     if(token == "quit") {
182       OpeningBook.close();
183       stop_threads();
184       quit_eval();
185       exit(0);
186     }
187     else if(token == "uci") {
188       std::cout << "id name " << engine_name() << std::endl;
189       std::cout << "id author Tord Romstad" << std::endl;
190       print_uci_options();
191       std::cout << "uciok" << std::endl;
192     }
193     else if(token == "ucinewgame") {
194       TT.clear();
195       Position::init_piece_square_tables();
196       RootPosition.from_fen(StartPosition);
197     }
198     else if(token == "isready")
199       std::cout << "readyok" << std::endl;
200     else if(token == "position")
201       set_position(uip);
202     else if(token == "setoption")
203       set_option(uip);
204     else if(token == "go")
205       go(uip);
206
207     // The remaining commands are for debugging purposes only.
208     // Perhaps they should be removed later in order to reduce the
209     // size of the program binary.
210     else if(token == "d")
211       RootPosition.print();
212     else if(token == "flip") {
213       Position p(RootPosition);
214       RootPosition.flipped_copy(p);
215     }
216     else if(token == "eval") {
217       EvalInfo ei;
218       std::cout << "Incremental mg: " << RootPosition.mg_value()
219                 << std::endl;
220       std::cout << "Incremental eg: " << RootPosition.eg_value()
221                 << std::endl;
222       std::cout << "Full eval: "
223                 << evaluate(RootPosition, ei, 0)
224                 << std::endl;
225     }
226     else if(token == "key") {
227       std::cout << "key: " << RootPosition.get_key()
228                 << " material key: " << RootPosition.get_material_key()
229                 << " pawn key: " << RootPosition.get_pawn_key()
230                 << std::endl;
231     }
232     else {
233       std::cout << "Unknown command: " << command << std::endl;
234       while(!uip.at_end_of_line()) {
235         std::cout << uip.get_next_token() << std::endl;
236       }
237     }
238   }
239
240
241   // set_position() is called when Glaurung receives the "position" UCI
242   // command.  The input parameter is a UCIInputParser.  It is assumed
243   // that this parser has consumed the first token of the UCI command
244   // ("position"), and is ready to read the second token ("startpos"
245   // or "fen", if the input is well-formed).
246
247   void set_position(UCIInputParser &uip) {
248
249     std::string token;
250
251     token = uip.get_next_token();
252     if(token == "startpos")
253       RootPosition.from_fen(StartPosition);
254     else if(token == "fen") {
255       std::string fen;
256       while(token != "moves" && !uip.at_end_of_line()) {
257         token = uip.get_next_token();
258         fen += token;
259         fen += ' ';
260       }
261       RootPosition.from_fen(fen);
262     }
263
264     if(!uip.at_end_of_line()) {
265       if(token != "moves")
266         token = uip.get_next_token();
267       if(token == "moves") {
268         Move move;
269         UndoInfo u;
270         while(!uip.at_end_of_line()) {
271           token = uip.get_next_token();
272           move = move_from_string(RootPosition, token);
273           RootPosition.do_move(move, u);
274           if(RootPosition.rule_50_counter() == 0)
275             RootPosition.reset_game_ply();
276         }
277       }
278     }
279   }
280
281
282   // set_option() is called when Glaurung receives the "setoption" UCI
283   // command.  The input parameter is a UCIInputParser.  It is assumed
284   // that this parser has consumed the first token of the UCI command
285   // ("setoption"), and is ready to read the second token ("name", if
286   // the input is well-formed).
287
288   void set_option(UCIInputParser &uip) {
289
290     std::string token;
291
292     if(!uip.at_end_of_line()) {
293       token = uip.get_next_token();
294       if(token == "name" && !uip.at_end_of_line()) {
295         std::string name = uip.get_next_token();
296         std::string nextToken;
297         while(!uip.at_end_of_line()
298               && (nextToken = uip.get_next_token()) != "value")
299           name += (" " + nextToken);
300         if(nextToken == "value")
301           set_option_value(name, uip.get_rest_of_line());
302         else
303           push_button(name);
304       }
305     }
306   }
307
308
309   // go() is called when Glaurung receives the "go" UCI command.  The
310   // input parameter is a UCIInputParser.  It is assumed that this
311   // parser has consumed the first token of the UCI command ("go"),
312   // and is ready to read the second token.  The function sets the
313   // thinking time and other parameters from the input string, and
314   // calls think() (defined in search.cpp) with the appropriate
315   // parameters.
316
317   void go(UCIInputParser &uip) {
318
319     std::string token;
320
321     int time[2] = {0, 0}, inc[2] = {0, 0}, movesToGo = 0, depth = 0, nodes = 0;
322     int moveTime = 0;
323     bool infinite = false, ponder = false;
324     Move searchMoves[500];
325
326     searchMoves[0] = MOVE_NONE;
327
328     while(!uip.at_end_of_line()) {
329       token = uip.get_next_token();
330
331       if(token == "infinite")
332         infinite = true;
333       else if(token == "ponder")
334         ponder = true;
335       else if(token == "wtime") {
336         if(!uip.at_end_of_line())
337           time[0] = atoi(uip.get_next_token().c_str());
338       }
339       else if(token == "btime") {
340         if(!uip.at_end_of_line())
341           time[1] = atoi(uip.get_next_token().c_str());
342       }
343       else if(token == "winc") {
344         if(!uip.at_end_of_line())
345           inc[0] = atoi(uip.get_next_token().c_str());
346       }
347       else if(token == "binc") {
348         if(!uip.at_end_of_line())
349           inc[1] = atoi(uip.get_next_token().c_str());
350       }
351       else if(token == "movestogo") {
352         if(!uip.at_end_of_line())
353           movesToGo = atoi(uip.get_next_token().c_str());
354       }
355       else if(token == "depth") {
356         if(!uip.at_end_of_line())
357           depth = atoi(uip.get_next_token().c_str());
358       }
359       else if(token == "nodes") {
360         if(!uip.at_end_of_line())
361           nodes = atoi(uip.get_next_token().c_str());
362       }
363       else if(token == "movetime") {
364         if(!uip.at_end_of_line())
365           moveTime = atoi(uip.get_next_token().c_str());
366       }
367       else if(token == "searchmoves" && !uip.at_end_of_line()) {
368         int numOfMoves = 0;
369         while(!uip.at_end_of_line()) {
370           token = uip.get_next_token();
371           searchMoves[numOfMoves++] = move_from_string(RootPosition, token);
372         }
373         searchMoves[numOfMoves] = MOVE_NONE;
374       }
375     }
376
377     if(moveTime)
378       infinite = true;  // HACK
379
380     think(RootPosition, infinite, ponder, time[RootPosition.side_to_move()],
381           inc[RootPosition.side_to_move()], movesToGo, depth, nodes, moveTime,
382           searchMoves);
383   }
384   
385 }