From: Sebastian Buchwald Date: Mon, 4 Sep 2023 20:01:20 +0000 (+0200) Subject: Avoid "using namespace std" X-Git-Url: https://git.sesse.net/?p=stockfish;a=commitdiff_plain;h=a8b4fd16716e74a9819e798fc09e5926e003013e Avoid "using namespace std" This is a cleanup PR that prepares the automatic checking of missing or superfluous #include directives via the include-what-you-use (IWYU) tool on the CI. Unfortunately, IWYU proposes additional includes for "namespace std" although we don't need them. To avoid the problem, the commit removes all "using namespace std" statements from the code and directly uses the std:: prefix instead. Alternatively, we could add specific usings (e.g. "using std::string") foreach used type. Also, a mix of both approaches would be possible. I decided for the prefix approach because most of the files were already using the std:: prefixes despite the "using namespace std". closes https://github.com/official-stockfish/Stockfish/pull/4772 No functional change --- diff --git a/src/benchmark.cpp b/src/benchmark.cpp index f3401c61..8e28184a 100644 --- a/src/benchmark.cpp +++ b/src/benchmark.cpp @@ -25,11 +25,9 @@ #include "position.h" -using namespace std; - namespace { -const vector Defaults = { +const std::vector Defaults = { "setoption name UCI_Chess960 value false", "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 10", @@ -109,17 +107,17 @@ namespace Stockfish { /// bench 64 4 5000 current movetime : search current position with 4 threads for 5 sec /// bench 16 1 5 blah perft : run a perft 5 on positions in file "blah" -vector setup_bench(const Position& current, istream& is) { +std::vector setup_bench(const Position& current, std::istream& is) { - vector fens, list; - string go, token; + std::vector fens, list; + std::string go, token; // Assign default values to missing arguments - string ttSize = (is >> token) ? token : "16"; - string threads = (is >> token) ? token : "1"; - string limit = (is >> token) ? token : "13"; - string fenFile = (is >> token) ? token : "default"; - string limitType = (is >> token) ? token : "depth"; + std::string ttSize = (is >> token) ? token : "16"; + std::string threads = (is >> token) ? token : "1"; + std::string limit = (is >> token) ? token : "13"; + std::string fenFile = (is >> token) ? token : "default"; + std::string limitType = (is >> token) ? token : "depth"; go = limitType == "eval" ? "eval" : "go " + limitType + " " + limit; @@ -131,12 +129,12 @@ vector setup_bench(const Position& current, istream& is) { else { - string fen; - ifstream file(fenFile); + std::string fen; + std::ifstream file(fenFile); if (!file.is_open()) { - cerr << "Unable to open file " << fenFile << endl; + std::cerr << "Unable to open file " << fenFile << std::endl; exit(EXIT_FAILURE); } @@ -151,8 +149,8 @@ vector setup_bench(const Position& current, istream& is) { list.emplace_back("setoption name Hash value " + ttSize); list.emplace_back("ucinewgame"); - for (const string& fen : fens) - if (fen.find("setoption") != string::npos) + for (const std::string& fen : fens) + if (fen.find("setoption") != std::string::npos) list.emplace_back(fen); else { diff --git a/src/evaluate.cpp b/src/evaluate.cpp index 46ebbb49..9ca0e456 100644 --- a/src/evaluate.cpp +++ b/src/evaluate.cpp @@ -51,13 +51,11 @@ #endif -using namespace std; - namespace Stockfish { namespace Eval { - string currentEvalFileName = "None"; + std::string currentEvalFileName = "None"; /// NNUE::init() tries to load a NNUE network at startup time, or when the engine /// receives a UCI command "setoption name EvalFile value nn-[a-z0-9]{12}.nnue" @@ -69,22 +67,22 @@ namespace Eval { void NNUE::init() { - string eval_file = string(Options["EvalFile"]); + std::string eval_file = std::string(Options["EvalFile"]); if (eval_file.empty()) eval_file = EvalFileDefaultName; #if defined(DEFAULT_NNUE_DIRECTORY) - vector dirs = { "" , "" , CommandLine::binaryDirectory , stringify(DEFAULT_NNUE_DIRECTORY) }; + std::vector dirs = { "" , "" , CommandLine::binaryDirectory , stringify(DEFAULT_NNUE_DIRECTORY) }; #else - vector dirs = { "" , "" , CommandLine::binaryDirectory }; + std::vector dirs = { "" , "" , CommandLine::binaryDirectory }; #endif - for (const string& directory : dirs) + for (const std::string& directory : dirs) if (currentEvalFileName != eval_file) { if (directory != "") { - ifstream stream(directory + eval_file, ios::binary); + std::ifstream stream(directory + eval_file, std::ios::binary); if (NNUE::load_eval(eval_file, stream)) currentEvalFileName = eval_file; } @@ -92,7 +90,7 @@ namespace Eval { if (directory == "" && eval_file == EvalFileDefaultName) { // C++ way to prepare a buffer for a memory stream - class MemoryBuffer : public basic_streambuf { + class MemoryBuffer : public std::basic_streambuf { public: MemoryBuffer(char* p, size_t n) { setg(p, p, p + n); setp(p, p + n); } }; @@ -100,7 +98,7 @@ namespace Eval { size_t(gEmbeddedNNUESize)); (void) gEmbeddedNNUEEnd; // Silence warning on unused variable - istream stream(&buffer); + std::istream stream(&buffer); if (NNUE::load_eval(eval_file, stream)) currentEvalFileName = eval_file; } @@ -110,18 +108,18 @@ namespace Eval { /// NNUE::verify() verifies that the last net used was loaded successfully void NNUE::verify() { - string eval_file = string(Options["EvalFile"]); + std::string eval_file = std::string(Options["EvalFile"]); if (eval_file.empty()) eval_file = EvalFileDefaultName; if (currentEvalFileName != eval_file) { - string msg1 = "Network evaluation parameters compatible with the engine must be available."; - string msg2 = "The network file " + eval_file + " was not loaded successfully."; - string msg3 = "The UCI option EvalFile might need to specify the full path, including the directory name, to the network file."; - string msg4 = "The default net can be downloaded from: https://tests.stockfishchess.org/api/nn/" + std::string(EvalFileDefaultName); - string msg5 = "The engine will be terminated now."; + std::string msg1 = "Network evaluation parameters compatible with the engine must be available."; + std::string msg2 = "The network file " + eval_file + " was not loaded successfully."; + std::string msg3 = "The UCI option EvalFile might need to specify the full path, including the directory name, to the network file."; + std::string msg4 = "The default net can be downloaded from: https://tests.stockfishchess.org/api/nn/" + std::string(EvalFileDefaultName); + std::string msg5 = "The engine will be terminated now."; sync_cout << "info string ERROR: " << msg1 << sync_endl; sync_cout << "info string ERROR: " << msg2 << sync_endl; diff --git a/src/misc.cpp b/src/misc.cpp index 42083e0a..a72a1c13 100644 --- a/src/misc.cpp +++ b/src/misc.cpp @@ -67,14 +67,12 @@ using fun8_t = bool(*)(HANDLE, BOOL, PTOKEN_PRIVILEGES, DWORD, PTOKEN_PRIVILEGES #include #endif -using namespace std; - namespace Stockfish { namespace { /// Version number or dev. -constexpr string_view version = "dev"; +constexpr std::string_view version = "dev"; /// Our fancy logging facility. The trick here is to replace cin.rdbuf() and /// cout.rdbuf() with two Tie objects that tie cin and cout to a file stream. We @@ -82,16 +80,16 @@ constexpr string_view version = "dev"; /// usual I/O functionality, all without changing a single line of code! /// Idea from http://groups.google.com/group/comp.lang.c++/msg/1d941c0f26ea0d81 -struct Tie: public streambuf { // MSVC requires split streambuf for cin and cout +struct Tie: public std::streambuf { // MSVC requires split streambuf for cin and cout - Tie(streambuf* b, streambuf* l) : buf(b), logBuf(l) {} + Tie(std::streambuf* b, std::streambuf* l) : buf(b), logBuf(l) {} int sync() override { return logBuf->pubsync(), buf->pubsync(); } int overflow(int c) override { return log(buf->sputc((char)c), "<< "); } int underflow() override { return buf->sgetc(); } int uflow() override { return log(buf->sbumpc(), ">> "); } - streambuf *buf, *logBuf; + std::streambuf *buf, *logBuf; int log(int c, const char* prefix) { @@ -106,10 +104,10 @@ struct Tie: public streambuf { // MSVC requires split streambuf for cin and cout class Logger { - Logger() : in(cin.rdbuf(), file.rdbuf()), out(cout.rdbuf(), file.rdbuf()) {} + Logger() : in(std::cin.rdbuf(), file.rdbuf()), out(std::cout.rdbuf(), file.rdbuf()) {} ~Logger() { start(""); } - ofstream file; + std::ofstream file; Tie in, out; public: @@ -119,23 +117,23 @@ public: if (l.file.is_open()) { - cout.rdbuf(l.out.buf); - cin.rdbuf(l.in.buf); + std::cout.rdbuf(l.out.buf); + std::cin.rdbuf(l.in.buf); l.file.close(); } if (!fname.empty()) { - l.file.open(fname, ifstream::out); + l.file.open(fname, std::ifstream::out); if (!l.file.is_open()) { - cerr << "Unable to open debug log file " << fname << endl; + std::cerr << "Unable to open debug log file " << fname << std::endl; exit(EXIT_FAILURE); } - cin.rdbuf(&l.in); - cout.rdbuf(&l.out); + std::cin.rdbuf(&l.in); + std::cout.rdbuf(&l.out); } } }; @@ -153,9 +151,9 @@ public: /// For releases (non dev builds) we only include the version number: /// Stockfish version -string engine_info(bool to_uci) { - stringstream ss; - ss << "Stockfish " << version << setfill('0'); +std::string engine_info(bool to_uci) { + std::stringstream ss; + ss << "Stockfish " << version << std::setfill('0'); if constexpr (version == "dev") { @@ -163,12 +161,12 @@ string engine_info(bool to_uci) { #ifdef GIT_DATE ss << stringify(GIT_DATE); #else - constexpr string_view months("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"); - string month, day, year; - stringstream date(__DATE__); // From compiler, format is "Sep 21 2008" + constexpr std::string_view months("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"); + std::string month, day, year; + std::stringstream date(__DATE__); // From compiler, format is "Sep 21 2008" date >> month >> day >> year; - ss << year << setw(2) << setfill('0') << (1 + months.find(month) / 4) << setw(2) << setfill('0') << day; + ss << year << std::setw(2) << std::setfill('0') << (1 + months.find(month) / 4) << std::setw(2) << std::setfill('0') << day; #endif ss << "-"; @@ -741,12 +739,12 @@ void bindThisThread(size_t idx) { namespace CommandLine { -string argv0; // path+name of the executable binary, as given by argv[0] -string binaryDirectory; // path of the executable directory -string workingDirectory; // path of the working directory +std::string argv0; // path+name of the executable binary, as given by argv[0] +std::string binaryDirectory; // path of the executable directory +std::string workingDirectory; // path of the working directory void init([[maybe_unused]] int argc, char* argv[]) { - string pathSeparator; + std::string pathSeparator; // extract the path+name of the executable binary argv0 = argv[0]; diff --git a/src/uci.cpp b/src/uci.cpp index 2a35a40f..f3e436ef 100644 --- a/src/uci.cpp +++ b/src/uci.cpp @@ -41,8 +41,6 @@ #include "search.h" #include "thread.h" -using namespace std; - namespace Stockfish { namespace { @@ -56,10 +54,10 @@ namespace { // the initial position ("startpos") and then makes the moves given in the following // move list ("moves"). - void position(Position& pos, istringstream& is, StateListPtr& states) { + void position(Position& pos, std::istringstream& is, StateListPtr& states) { Move m; - string token, fen; + std::string token, fen; is >> token; @@ -103,11 +101,11 @@ namespace { // setoption() is called when the engine receives the "setoption" UCI command. // The function updates the UCI option ("name") to the given value ("value"). - void setoption(istringstream& is) { + void setoption(std::istringstream& is) { Threads.main()->wait_for_search_finished(); - string token, name, value; + std::string token, name, value; is >> token; // Consume the "name" token @@ -130,10 +128,10 @@ namespace { // sets the thinking time and other parameters from the input string, then starts // with a search. - void go(Position& pos, istringstream& is, StateListPtr& states) { + void go(Position& pos, std::istringstream& is, StateListPtr& states) { Search::LimitsType limits; - string token; + std::string token; bool ponderMode = false; limits.startTime = now(); // The search starts as early as possible @@ -164,24 +162,24 @@ namespace { // Firstly, a list of UCI commands is set up according to the bench // parameters, then it is run one by one, printing a summary at the end. - void bench(Position& pos, istream& args, StateListPtr& states) { + void bench(Position& pos, std::istream& args, StateListPtr& states) { - string token; + std::string token; uint64_t num, nodes = 0, cnt = 1; - vector list = setup_bench(pos, args); - num = count_if(list.begin(), list.end(), [](const string& s) { return s.find("go ") == 0 || s.find("eval") == 0; }); + std::vector list = setup_bench(pos, args); + num = count_if(list.begin(), list.end(), [](const std::string& s) { return s.find("go ") == 0 || s.find("eval") == 0; }); TimePoint elapsed = now(); for (const auto& cmd : list) { - istringstream is(cmd); - is >> skipws >> token; + std::istringstream is(cmd); + is >> std::skipws >> token; if (token == "go" || token == "eval") { - cerr << "\nPosition: " << cnt++ << '/' << num << " (" << pos.fen() << ")" << endl; + std::cerr << "\nPosition: " << cnt++ << '/' << num << " (" << pos.fen() << ")" << std::endl; if (token == "go") { go(pos, is, states); @@ -200,10 +198,10 @@ namespace { dbg_print(); - cerr << "\n===========================" - << "\nTotal time (ms) : " << elapsed - << "\nNodes searched : " << nodes - << "\nNodes/second : " << 1000 * nodes / elapsed << endl; + std::cerr << "\n===========================" + << "\nTotal time (ms) : " << elapsed + << "\nNodes searched : " << nodes + << "\nNodes/second : " << 1000 * nodes / elapsed << std::endl; } // The win rate model returns the probability of winning (in per mille units) given an @@ -244,7 +242,7 @@ namespace { void UCI::loop(int argc, char* argv[]) { Position pos; - string token, cmd; + std::string token, cmd; StateListPtr states(new std::deque(1)); pos.set(StartFEN, false, &states->back(), Threads.main()); @@ -253,13 +251,13 @@ void UCI::loop(int argc, char* argv[]) { cmd += std::string(argv[i]) + " "; do { - if (argc == 1 && !getline(cin, cmd)) // Wait for an input or an end-of-file (EOF) indication + if (argc == 1 && !getline(std::cin, cmd)) // Wait for an input or an end-of-file (EOF) indication cmd = "quit"; - istringstream is(cmd); + std::istringstream is(cmd); token.clear(); // Avoid a stale if getline() returns nothing or a blank line - is >> skipws >> token; + is >> std::skipws >> token; if ( token == "quit" || token == "stop") @@ -294,7 +292,7 @@ void UCI::loop(int argc, char* argv[]) { { std::optional filename; std::string f; - if (is >> skipws >> f) + if (is >> std::skipws >> f) filename = f; Eval::NNUE::save_eval(filename); } @@ -325,11 +323,11 @@ int UCI::to_cp(Value v) { /// mate Mate in 'y' moves (not plies). If the engine is getting mated, /// uses negative values for 'y'. -string UCI::value(Value v) { +std::string UCI::value(Value v) { assert(-VALUE_INFINITE < v && v < VALUE_INFINITE); - stringstream ss; + std::stringstream ss; if (abs(v) < VALUE_TB_WIN_IN_MAX_PLY) ss << "cp " << UCI::to_cp(v); @@ -348,9 +346,9 @@ string UCI::value(Value v) { /// UCI::wdl() reports the win-draw-loss (WDL) statistics given an evaluation /// and a game ply based on the data gathered for fishtest LTC games. -string UCI::wdl(Value v, int ply) { +std::string UCI::wdl(Value v, int ply) { - stringstream ss; + std::stringstream ss; int wdl_w = win_rate_model( v, ply); int wdl_l = win_rate_model(-v, ply); @@ -373,7 +371,7 @@ std::string UCI::square(Square s) { /// standard chess mode and in e1h1 notation it is printed in Chess960 mode. /// Internally, all castling moves are always encoded as 'king captures rook'. -string UCI::move(Move m, bool chess960) { +std::string UCI::move(Move m, bool chess960) { if (m == MOVE_NONE) return "(none)"; @@ -387,7 +385,7 @@ string UCI::move(Move m, bool chess960) { if (type_of(m) == CASTLING && !chess960) to = make_square(to > from ? FILE_G : FILE_C, rank_of(from)); - string move = UCI::square(from) + UCI::square(to); + std::string move = UCI::square(from) + UCI::square(to); if (type_of(m) == PROMOTION) move += " pnbrqk"[promotion_type(m)]; @@ -399,7 +397,7 @@ string UCI::move(Move m, bool chess960) { /// UCI::to_move() converts a string representing a move in coordinate notation /// (g1f3, a7a8q) to the corresponding legal Move, if any. -Move UCI::to_move(const Position& pos, string& str) { +Move UCI::to_move(const Position& pos, std::string& str) { if (str.length() == 5) str[4] = char(tolower(str[4])); // The promotion piece character must be lowercased