From 84b8080cf6779f14331cf908f71074eae369e8e8 Mon Sep 17 00:00:00 2001 From: Stephan Kantelberg Date: Thu, 5 May 2022 21:29:03 +0200 Subject: [PATCH 1/7] update clang-format and clang-tidy files --- .clang-format | 35 +++++++++++++++++------------------ .clang-tidy | 20 ++++++++++++++++---- 2 files changed, 33 insertions(+), 22 deletions(-) diff --git a/.clang-format b/.clang-format index 4ede542..ad2ec5b 100644 --- a/.clang-format +++ b/.clang-format @@ -1,12 +1,12 @@ AccessModifierOffset: -2 AlignAfterOpenBracket: DontAlign -AlignConsecutiveAssignments: false -AlignConsecutiveDeclarations: false +AlignConsecutiveAssignments: None +AlignConsecutiveDeclarations: None AlignEscapedNewlines: Left AlignOperands: true AlignTrailingComments: false AllowAllParametersOfDeclarationOnNextLine: false -AllowShortBlocksOnASingleLine: true +AllowShortBlocksOnASingleLine: Always AllowShortCaseLabelsOnASingleLine: false AllowShortFunctionsOnASingleLine: All AllowShortIfStatementsOnASingleLine: true @@ -14,7 +14,7 @@ AllowShortLoopsOnASingleLine: true AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: true -AlwaysBreakTemplateDeclarations: false +AlwaysBreakTemplateDeclarations: No BinPackArguments: false BinPackParameters: false BraceWrapping: @@ -40,7 +40,7 @@ BreakBeforeTernaryOperators: true BreakConstructorInitializers: BeforeColon BreakConstructorInitializersBeforeComma: false BreakStringLiterals: true -ColumnLimit: 0 +ColumnLimit: 180 CommentPragmas: '^ IWYU pragma:' CompactNamespaces: false ConstructorInitializerAllOnOneLineOrOnePerLine: false @@ -52,19 +52,19 @@ DisableFormat: false ExperimentalAutoDetectBinPacking: true FixNamespaceComments: true ForEachMacros: -- foreach -- Q_FOREACH -- BOOST_FOREACH + - foreach + - Q_FOREACH + - BOOST_FOREACH IncludeCategories: -- Priority: 2 - Regex: ^"(llvm|llvm-c|clang|clang-c)/ -- Priority: 3 - Regex: ^(<|"(gtest|gmock|isl|json)/) -- Priority: 1 - Regex: .* + - Priority: 2 + Regex: ^"(llvm|llvm-c|clang|clang-c)/ + - Priority: 3 + Regex: ^(<|"(gtest|gmock|isl|json)/) + - Priority: 1 + Regex: .* IncludeIsMainRegex: (Test)?$ IndentCaseLabels: false -IndentWidth: 2 +IndentWidth: 4 IndentWrappedFunctionNames: true JavaScriptQuotes: Leave JavaScriptWrapImports: true @@ -79,7 +79,7 @@ ObjCSpaceAfterProperty: true ObjCSpaceBeforeProtocolList: false PointerAlignment: Right ReflowComments: true -SortIncludes: false +SortIncludes: CaseSensitive SortUsingDeclarations: false SpaceAfterCStyleCast: false SpaceAfterTemplateKeyword: false @@ -92,7 +92,6 @@ SpacesInCStyleCastParentheses: false SpacesInContainerLiterals: true SpacesInParentheses: false SpacesInSquareBrackets: false -Standard: Cpp11 +Standard: c++20 TabWidth: 8 UseTab: Never - diff --git a/.clang-tidy b/.clang-tidy index f95f74f..5978ff9 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,7 +1,19 @@ --- -Checks: '*,-fuchsia-*,-google-*,-zircon-*,-abseil-*,-modernize-use-trailing-return-type,-llvm*' -WarningsAsErrors: '*' +Checks: "*, + -abseil-*, + -altera-*, + -android-*, + -fuchsia-*, + -google-*, + -llvm*, + -modernize-use-trailing-return-type, + -zircon-*, + -readability-else-after-return, + -readability-static-accessed-through-instance, + -readability-avoid-const-params-in-decls, + -cppcoreguidelines-non-private-member-variables-in-classes, + -misc-non-private-member-variables-in-classes, +" +WarningsAsErrors: '' HeaderFilterRegex: '' FormatStyle: none - - From 9daaecdc5086a405efa188a105550797712a215f Mon Sep 17 00:00:00 2001 From: Stephan Kantelberg Date: Thu, 5 May 2022 21:32:24 +0200 Subject: [PATCH 2/7] update files with new formatting --- fuzz_test/fuzz_tester.cpp | 16 +++--- src/boost.beast/data.h | 4 +- src/boost.beast/error_handling.h | 4 +- src/boost.beast/listener.h | 21 +++----- src/boost.beast/main.cpp | 5 +- src/boost.beast/request.h | 20 +++----- src/boost.beast/session.h | 18 ++----- src/main.cpp | 20 ++++---- src/sml/actions.h | 16 +++--- src/sml/logger.h | 54 +++++++++----------- src/sml/main.cpp | 60 +++++++++++----------- src/sml/plantumlDump.h | 86 +++++++++++++------------------- test/catch2/constexpr_tests.cpp | 13 ++--- test/catch2/tests.cpp | 13 ++--- test/gtest/constexpr_tests.cpp | 13 ++--- test/gtest/gtest_main.cpp | 5 +- test/gtest/tests.cpp | 13 ++--- 17 files changed, 158 insertions(+), 223 deletions(-) diff --git a/fuzz_test/fuzz_tester.cpp b/fuzz_test/fuzz_tester.cpp index 49217aa..7ffb452 100644 --- a/fuzz_test/fuzz_tester.cpp +++ b/fuzz_test/fuzz_tester.cpp @@ -1,22 +1,20 @@ +#include #include #include -#include [[nodiscard]] auto sum_values(const uint8_t *Data, size_t Size) { - constexpr auto scale = 1000; + constexpr auto scale = 1000; - int value = 0; - for (std::size_t offset = 0; offset < Size; ++offset) { - value += static_cast(*std::next(Data, static_cast(offset))) * scale; - } - return value; + int value = 0; + for (std::size_t offset = 0; offset < Size; ++offset) { value += static_cast(*std::next(Data, static_cast(offset))) * scale; } + return value; } // Fuzzer that attempts to invoke undefined behavior for signed integer overflow // cppcheck-suppress unusedFunction symbolName=LLVMFuzzerTestOneInput extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { - fmt::print("Value sum: {}, len{}\n", sum_values(Data,Size), Size); - return 0; + fmt::print("Value sum: {}, len{}\n", sum_values(Data, Size), Size); + return 0; } diff --git a/src/boost.beast/data.h b/src/boost.beast/data.h index 380e298..9536ad4 100644 --- a/src/boost.beast/data.h +++ b/src/boost.beast/data.h @@ -8,8 +8,8 @@ struct person { std::string name; std::string address; - int age = {0}; - int id = {0}; + int age = { 0 }; + int id = { 0 }; }; inline void to_json(nlohmann::json &j, const person &p) { j = nlohmann::json{ { "name", p.name }, { "address", p.address }, { "age", p.age }, { "id", p.id } }; } diff --git a/src/boost.beast/error_handling.h b/src/boost.beast/error_handling.h index 581a0fc..3f52332 100644 --- a/src/boost.beast/error_handling.h +++ b/src/boost.beast/error_handling.h @@ -1,9 +1,9 @@ #pragma once +#include +#include #include #include #include -#include -#include #include // from diff --git a/src/boost.beast/listener.h b/src/boost.beast/listener.h index fa03bfb..fb1a305 100644 --- a/src/boost.beast/listener.h +++ b/src/boost.beast/listener.h @@ -1,6 +1,6 @@ #pragma once -#include "error_handling.h" #include "data.h" +#include "error_handling.h" #include "session.h" // Accepts incoming connections and launches the sessions @@ -13,32 +13,28 @@ class Listener : public std::enable_shared_from_this // Open the acceptor m_acceptor.open(endpoint.protocol(), ec); - if (ec) - { + if (ec) { fail(ec, "open"); return; } // Allow address reuse m_acceptor.set_option(asio::socket_base::reuse_address(true), ec); - if (ec) - { + if (ec) { fail(ec, "set_option"); return; } // Bind to the server address m_acceptor.bind(endpoint, ec); - if (ec) - { + if (ec) { fail(ec, "bind"); return; } // Start listening for connections m_acceptor.listen(asio::socket_base::max_listen_connections, ec); - if (ec) - { + if (ec) { fail(ec, "listen"); return; } @@ -56,12 +52,9 @@ class Listener : public std::enable_shared_from_this void onAccept(beast::error_code ec, tcp::socket socket) { - if (ec) - { + if (ec) { fail(ec, "accept"); - } - else - { + } else { // Create the session and run it std::make_shared(std::move(socket), m_persons)->run(); } diff --git a/src/boost.beast/main.cpp b/src/boost.beast/main.cpp index 49c764f..c2b3b15 100644 --- a/src/boost.beast/main.cpp +++ b/src/boost.beast/main.cpp @@ -1,8 +1,8 @@ +#include "listener.h" #include #include #include #include -#include "listener.h" int main() @@ -20,8 +20,7 @@ int main() // Run the I/O service on the requested number of threads std::vector v; v.reserve(threads); - for (auto i = 0; i < threads; i++) - { + for (auto i = 0; i < threads; i++) { v.emplace_back([&ioc] { ioc.run(); }); } ioc.run(); diff --git a/src/boost.beast/request.h b/src/boost.beast/request.h index afbd86d..ba73195 100644 --- a/src/boost.beast/request.h +++ b/src/boost.beast/request.h @@ -26,20 +26,17 @@ template inline void handleRequest(http }; // Make sure we can handle the method - switch (req.method()) - { + switch (req.method()) { case http::verb::get: { // Respond to GET request nlohmann::json j = data; return send(std::move(createResponse(req, http::status::ok, j))); } case http::verb::put: { - try - { + try { const auto j = nlohmann::json::parse(req.body()); const data::person d = j; - if (d.id > data.size() - 1 || d.id < 0) - { + if (d.id > data.size() - 1 || d.id < 0) { const nlohmann::json j = R"({"error": "id is larger than data list or negative"})"; return send(std::move(createResponse(req, http::status::internal_server_error, j))); } @@ -48,22 +45,17 @@ template inline void handleRequest(http temp.address = d.address; temp.age = d.age; return send(std::move(createResponse(req, http::status::ok, j))); - } - catch (nlohmann::json::exception &e) - { + } catch (nlohmann::json::exception &e) { return send(std::move(badRequest(e.what()))); } } case http::verb::post: { - try - { + try { const auto j = nlohmann::json::parse(req.body()); data.push_back(j); data.back().id = static_cast(data.size()); return send(std::move(createResponse(req, http::status::ok, j))); - } - catch (nlohmann::json::exception &e) - { + } catch (nlohmann::json::exception &e) { return send(std::move(badRequest(e.what()))); } } diff --git a/src/boost.beast/session.h b/src/boost.beast/session.h index 1130348..6a764b2 100644 --- a/src/boost.beast/session.h +++ b/src/boost.beast/session.h @@ -37,15 +37,9 @@ class Session : public std::enable_shared_from_this boost::ignore_unused(bytes_transferred); // This means they closed the connection - if (ec == http::error::end_of_stream) - { - return doClose(); - } + if (ec == http::error::end_of_stream) { return doClose(); } - if (ec) - { - return fail(ec, "read"); - } + if (ec) { return fail(ec, "read"); } // Send the response handleRequest(std::move(m_req), m_lambda, m_person); @@ -55,13 +49,9 @@ class Session : public std::enable_shared_from_this { boost::ignore_unused(bytes_transferred); - if (ec) - { - return fail(ec, "write"); - } + if (ec) { return fail(ec, "write"); } - if (close) - { + if (close) { // This means we should close the connection, usually because // the response indicated the "Connection: close" semantic. return doClose(); diff --git a/src/main.cpp b/src/main.cpp index 2a4a58b..a57e3dd 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,8 +1,8 @@ #include #include -#include #include +#include static constexpr auto USAGE = R"(Naval Fate. @@ -24,18 +24,16 @@ static constexpr auto USAGE = int main(int argc, const char **argv) { - std::map args = docopt::docopt(USAGE, - { std::next(argv), std::next(argv, argc) }, - true,// show help if requested - "Naval Fate 2.0");// version string + std::map args = docopt::docopt(USAGE, + { std::next(argv), std::next(argv, argc) }, + true,// show help if requested + "Naval Fate 2.0");// version string - for (auto const &arg : args) { - std::cout << arg.first << arg.second << std::endl; - } + for (auto const &arg : args) { std::cout << arg.first << arg.second << std::endl; } - //Use the default logger (stdout, multi-threaded, colored) - spdlog::info("Hello, {}!", "World"); + // Use the default logger (stdout, multi-threaded, colored) + spdlog::info("Hello, {}!", "World"); - fmt::print("Hello, from {}\n", "{fmt}"); + fmt::print("Hello, from {}\n", "{fmt}"); } diff --git a/src/sml/actions.h b/src/sml/actions.h index a1558cc..d9673c3 100644 --- a/src/sml/actions.h +++ b/src/sml/actions.h @@ -4,19 +4,19 @@ std::chrono::time_point startTime; struct turnOffAction { - void operator()() { spdlog::info("turned off"); } + void operator()() { spdlog::info("turned off"); } } turnOffAction; struct startAction { - void operator()() { startTime = std::chrono::steady_clock::now(); } + void operator()() { startTime = std::chrono::steady_clock::now(); } } startAction; struct stopAction { - void operator()() - { - const auto diff = std::chrono::steady_clock::now() - startTime; - spdlog::info("Elasped time: {}s", std::chrono::duration_cast(diff).count()); - } -} stopAction; \ No newline at end of file + void operator()() + { + const auto diff = std::chrono::steady_clock::now() - startTime; + spdlog::info("Elasped time: {}s", std::chrono::duration_cast(diff).count()); + } +} stopAction; diff --git a/src/sml/logger.h b/src/sml/logger.h index dc79f28..1d43eb8 100644 --- a/src/sml/logger.h +++ b/src/sml/logger.h @@ -2,38 +2,30 @@ struct CustomLogger { - template - void log_process_event(const TEvent &) - { - spdlog::info("[{}][process_event] {}", boost::sml::aux::get_type_name(), boost::sml::aux::get_type_name()); - } + template void log_process_event(const TEvent &) + { + spdlog::info("[{}][process_event] {}", boost::sml::aux::get_type_name(), boost::sml::aux::get_type_name()); + } - template - void log_guard(const TGuard &, const TEvent &, bool result) - { - spdlog::info("[%s][guard] %s %s %s", boost::sml::aux::get_type_name(), boost::sml::aux::get_type_name(), boost::sml::aux::get_type_name(), (result ? "[OK]" : "[Reject]")); - } + template void log_guard(const TGuard &, const TEvent &, bool result) + { + spdlog::info("[%s][guard] %s %s %s", + boost::sml::aux::get_type_name(), + boost::sml::aux::get_type_name(), + boost::sml::aux::get_type_name(), + (result ? "[OK]" : "[Reject]")); + } - template - void log_action(const TAction &, const TEvent &) - { - spdlog::info("[{}][action] {} {}", boost::sml::aux::get_type_name(), boost::sml::aux::get_type_name(), boost::sml::aux::get_type_name()); - } + template void log_action(const TAction &, const TEvent &) + { + spdlog::info("[{}][action] {} {}", boost::sml::aux::get_type_name(), boost::sml::aux::get_type_name(), boost::sml::aux::get_type_name()); + } - template - void log_state_change(const TSrcState &src, const TDstState &dst) - { - spdlog::info("[{}][transition] {} -> {}", boost::sml::aux::get_type_name(), src.c_str(), dst.c_str()); - } + template void log_state_change(const TSrcState &src, const TDstState &dst) + { + spdlog::info("[{}][transition] {} -> {}", boost::sml::aux::get_type_name(), src.c_str(), dst.c_str()); + } - template - void log_process_event(const boost::sml::back::on_entry<_, TEvent> &) - { - spdlog::info("on_entry"); - } - template - void log_process_event(const boost::sml::back::on_exit<_, TEvent> &) - { - spdlog::info("on_exit"); - } -}; \ No newline at end of file + template void log_process_event(const boost::sml::back::on_entry<_, TEvent> &) { spdlog::info("on_entry"); } + template void log_process_event(const boost::sml::back::on_exit<_, TEvent> &) { spdlog::info("on_exit"); } +}; diff --git a/src/sml/main.cpp b/src/sml/main.cpp index 2be45cc..84c1b3c 100644 --- a/src/sml/main.cpp +++ b/src/sml/main.cpp @@ -2,16 +2,16 @@ * Example: * stop watch */ +#include "actions.h" +#include "events.h" +#include "logger.h" +#include "plantumlDump.h" +#include "states.h" #include #include -#include -#include #include -#include "logger.h" -#include "states.h" -#include "events.h" -#include "actions.h" -#include "plantumlDump.h" +#include +#include using namespace std::chrono_literals; @@ -20,47 +20,47 @@ namespace ReallyCoolSM { struct StopWatchStateMachine { - auto operator()() const noexcept - { - using namespace boost::sml; + auto operator()() const noexcept + { + using namespace boost::sml; - return make_transition_table( - // clang-format off + return make_transition_table( + // clang-format off *state + event = state , state + event / startAction = state , state + event / stopAction = state , state + event = state , state + event = state , state + event / turnOffAction = X - // clang-format on - ); - } + // clang-format on + ); + } }; }// namespace ReallyCoolSM int main() { - CustomLogger logger; - boost::sml::sm> sm{ logger }; + CustomLogger logger; + boost::sml::sm> sm{ logger }; - sm.process_event(turnOn{}); + sm.process_event(turnOn{}); - sm.process_event(start{}); - std::this_thread::sleep_for(1s); - sm.process_event(stop{}); + sm.process_event(start{}); + std::this_thread::sleep_for(1s); + sm.process_event(stop{}); - sm.process_event(reset{}); + sm.process_event(reset{}); - sm.process_event(start{}); + sm.process_event(start{}); - sm.process_event(reset{}); + sm.process_event(reset{}); - sm.process_event(start{}); - std::this_thread::sleep_for(1s); - sm.process_event(stop{}); + sm.process_event(start{}); + std::this_thread::sleep_for(1s); + sm.process_event(stop{}); - sm.process_event(turnOff{}); + sm.process_event(turnOff{}); - dump(sm); - return 0; + dump(sm); + return 0; } diff --git a/src/sml/plantumlDump.h b/src/sml/plantumlDump.h index 94a7833..5c32a73 100644 --- a/src/sml/plantumlDump.h +++ b/src/sml/plantumlDump.h @@ -3,70 +3,56 @@ namespace sml = boost::sml; -template -void dump_transition(std::ofstream &ofs) noexcept +template void dump_transition(std::ofstream &ofs) noexcept { - auto src_state = std::string{ sml::aux::string{}.c_str() }; - auto dst_state = std::string{ sml::aux::string{}.c_str() }; - if (dst_state == "X") { - dst_state = "[*]"; - } + auto src_state = std::string{ sml::aux::string{}.c_str() }; + auto dst_state = std::string{ sml::aux::string{}.c_str() }; + if (dst_state == "X") { dst_state = "[*]"; } - if (T::initial) { - ofs << "[*] --> " << src_state << "\n"; - } + if (T::initial) { ofs << "[*] --> " << src_state << "\n"; } - const auto has_event = !sml::aux::is_same::value; - const auto has_guard = !sml::aux::is_same::value; - const auto has_action = !sml::aux::is_same::value; + const auto has_event = !sml::aux::is_same::value; + const auto has_guard = !sml::aux::is_same::value; + const auto has_action = !sml::aux::is_same::value; - const auto is_entry = sml::aux::is_same>::value; - const auto is_exit = sml::aux::is_same>::value; + const auto is_entry = sml::aux::is_same>::value; + const auto is_exit = sml::aux::is_same>::value; - if (is_entry || is_exit) { - ofs << src_state; - } else {// state to state transition - ofs << src_state << " --> " << dst_state; - } + if (is_entry || is_exit) { + ofs << src_state; + } else {// state to state transition + ofs << src_state << " --> " << dst_state; + } - if (has_event || has_guard || has_action) { - ofs << " :"; - } + if (has_event || has_guard || has_action) { ofs << " :"; } - if (has_event) { - auto event = std::string(boost::sml::aux::get_type_name()); - if (is_entry) { - event = "entry"; - } else if (is_exit) { - event = "exit"; + if (has_event) { + auto event = std::string(boost::sml::aux::get_type_name()); + if (is_entry) { + event = "entry"; + } else if (is_exit) { + event = "exit"; + } + ofs << " " << event; } - ofs << " " << event; - } - if (has_guard) { - ofs << " [" << boost::sml::aux::get_type_name() << "]"; - } + if (has_guard) { ofs << " [" << boost::sml::aux::get_type_name() << "]"; } - if (has_action) { - ofs << " / " << boost::sml::aux::get_type_name(); - } + if (has_action) { ofs << " / " << boost::sml::aux::get_type_name(); } - ofs << "\n"; + ofs << "\n"; } -template class T, class... Ts> -void dump_transitions(std::ofstream &ofs, const T &) noexcept +template class T, class... Ts> void dump_transitions(std::ofstream &ofs, const T &) noexcept { - int _[]{ 0, (dump_transition(ofs), 0)... }; - (void)_; + int _[]{ 0, (dump_transition(ofs), 0)... }; + (void)_; } -template -void dump(const SM &) noexcept +template void dump(const SM &) noexcept { - std::ofstream ofs("stateMachine.plantuml"); - ofs << "@startuml\n\n"; - dump_transitions(ofs, typename SM::transitions{}); - ofs << std::endl - << "@enduml\n"; -} \ No newline at end of file + std::ofstream ofs("stateMachine.plantuml"); + ofs << "@startuml\n\n"; + dump_transitions(ofs, typename SM::transitions{}); + ofs << std::endl << "@enduml\n"; +} diff --git a/test/catch2/constexpr_tests.cpp b/test/catch2/constexpr_tests.cpp index 2bb5ea5..9fd3fde 100644 --- a/test/catch2/constexpr_tests.cpp +++ b/test/catch2/constexpr_tests.cpp @@ -1,14 +1,11 @@ #include -constexpr unsigned int Factorial(unsigned int number) -{ - return number <= 1 ? number : Factorial(number - 1) * number; -} +constexpr unsigned int Factorial(unsigned int number) { return number <= 1 ? number : Factorial(number - 1) * number; } TEST_CASE("Factorials are computed with constexpr", "[factorial]") { - STATIC_REQUIRE(Factorial(1) == 1); - STATIC_REQUIRE(Factorial(2) == 2); - STATIC_REQUIRE(Factorial(3) == 6); - STATIC_REQUIRE(Factorial(10) == 3628800); + STATIC_REQUIRE(Factorial(1) == 1); + STATIC_REQUIRE(Factorial(2) == 2); + STATIC_REQUIRE(Factorial(3) == 6); + STATIC_REQUIRE(Factorial(10) == 3628800); } diff --git a/test/catch2/tests.cpp b/test/catch2/tests.cpp index 9c40b28..028d2bc 100644 --- a/test/catch2/tests.cpp +++ b/test/catch2/tests.cpp @@ -1,14 +1,11 @@ #include -unsigned int Factorial(unsigned int number) -{ - return number <= 1 ? number : Factorial(number - 1) * number; -} +unsigned int Factorial(unsigned int number) { return number <= 1 ? number : Factorial(number - 1) * number; } TEST_CASE("Factorials are computed", "[factorial]") { - REQUIRE(Factorial(1) == 1); - REQUIRE(Factorial(2) == 2); - REQUIRE(Factorial(3) == 6); - REQUIRE(Factorial(10) == 3628800); + REQUIRE(Factorial(1) == 1); + REQUIRE(Factorial(2) == 2); + REQUIRE(Factorial(3) == 6); + REQUIRE(Factorial(10) == 3628800); } diff --git a/test/gtest/constexpr_tests.cpp b/test/gtest/constexpr_tests.cpp index ef56cff..ec2be6b 100644 --- a/test/gtest/constexpr_tests.cpp +++ b/test/gtest/constexpr_tests.cpp @@ -1,15 +1,12 @@ #include -constexpr unsigned int Factorial(unsigned int number) -{ - return number <= 1 ? number : Factorial(number - 1) * number; -} +constexpr unsigned int Factorial(unsigned int number) { return number <= 1 ? number : Factorial(number - 1) * number; } // NOLINTNEXTLINE(*) TEST(factorial, Factorials_are_computed_with_constexpr) { - static_assert(Factorial(1) == 1); - static_assert(Factorial(2) == 2); - static_assert(Factorial(3) == 6);//NOLINT(cppcoreguidelines-avoid-magic-numbers, readability-magic-numbers) - static_assert(Factorial(10) == 3628800);//NOLINT(cppcoreguidelines-avoid-magic-numbers, readability-magic-numbers) + static_assert(Factorial(1) == 1); + static_assert(Factorial(2) == 2); + static_assert(Factorial(3) == 6);// NOLINT(cppcoreguidelines-avoid-magic-numbers, readability-magic-numbers) + static_assert(Factorial(10) == 3628800);// NOLINT(cppcoreguidelines-avoid-magic-numbers, readability-magic-numbers) } diff --git a/test/gtest/gtest_main.cpp b/test/gtest/gtest_main.cpp index 5263cc8..96d7200 100644 --- a/test/gtest/gtest_main.cpp +++ b/test/gtest/gtest_main.cpp @@ -2,7 +2,6 @@ int main(int argc, char **argv) { - ::testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); } - diff --git a/test/gtest/tests.cpp b/test/gtest/tests.cpp index de22684..c262755 100644 --- a/test/gtest/tests.cpp +++ b/test/gtest/tests.cpp @@ -1,15 +1,12 @@ #include -unsigned int Factorial(unsigned int number) -{ - return number <= 1 ? number : Factorial(number - 1) * number; -} +unsigned int Factorial(unsigned int number) { return number <= 1 ? number : Factorial(number - 1) * number; } // NOLINTNEXTLINE(*) TEST(factorial, Factorials_are_computed) { - ASSERT_EQ(Factorial(1), 1); - ASSERT_EQ(Factorial(2), 2); - ASSERT_EQ(Factorial(3), 6); - ASSERT_EQ(Factorial(10), 3628800); + ASSERT_EQ(Factorial(1), 1); + ASSERT_EQ(Factorial(2), 2); + ASSERT_EQ(Factorial(3), 6); + ASSERT_EQ(Factorial(10), 3628800); } From 18c392efb68ebfbeda0bd38452969accb1624a1b Mon Sep 17 00:00:00 2001 From: Stephan Kantelberg Date: Thu, 5 May 2022 22:05:39 +0200 Subject: [PATCH 3/7] format CMakeLists.txt to have consistent style --- CMakeLists.txt | 105 ++++++++++++++++++------------------- fuzz_test/CMakeLists.txt | 22 ++++---- test/CMakeLists.txt | 4 +- test/catch2/CMakeLists.txt | 96 ++++++++++++++++----------------- test/gtest/CMakeLists.txt | 43 ++++++++------- 5 files changed, 134 insertions(+), 136 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 5a675a7..676072c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,80 +1,79 @@ -cmake_minimum_required(VERSION 3.15) +CMAKE_MINIMUM_REQUIRED(VERSION 3.15) # Set the project name to your project name, my project isn't very descriptive -project(myproject CXX) -include(cmake/StandardProjectSettings.cmake) -include(cmake/PreventInSourceBuilds.cmake) +PROJECT(myproject CXX) +INCLUDE(cmake/StandardProjectSettings.cmake) +INCLUDE(cmake/PreventInSourceBuilds.cmake) -include(cmake/CodeFormat.cmake) +INCLUDE(cmake/CodeFormat.cmake) # Link this 'library' to set the c++ standard / compile-time options requested -add_library(project_options INTERFACE) -target_compile_features(project_options INTERFACE cxx_std_17) +ADD_LIBRARY(project_options INTERFACE) +TARGET_COMPILE_FEATURES(project_options INTERFACE cxx_std_17) -if(CMAKE_CXX_COMPILER_ID MATCHES ".*Clang") - option(ENABLE_BUILD_WITH_TIME_TRACE "Enable -ftime-trace to generate time tracing .json files on clang" OFF) - if(ENABLE_BUILD_WITH_TIME_TRACE) - target_compile_options(project_options INTERFACE -ftime-trace) - endif() -endif() +IF(CMAKE_CXX_COMPILER_ID MATCHES ".*Clang") + OPTION(ENABLE_BUILD_WITH_TIME_TRACE "Enable -ftime-trace to generate time tracing .json files on clang" OFF) + IF(ENABLE_BUILD_WITH_TIME_TRACE) + TARGET_COMPILE_OPTIONS(project_options INTERFACE -ftime-trace) + ENDIF() +ENDIF() # Link this 'library' to use the warnings specified in CompilerWarnings.cmake -add_library(project_warnings INTERFACE) +ADD_LIBRARY(project_warnings INTERFACE) # enable cache system -include(cmake/Cache.cmake) +INCLUDE(cmake/Cache.cmake) # standard compiler warnings -include(cmake/CompilerWarnings.cmake) -set_project_warnings(project_warnings) +INCLUDE(cmake/CompilerWarnings.cmake) +SET_PROJECT_WARNINGS(project_warnings) # sanitizer options if supported by compiler -include(cmake/Sanitizers.cmake) -enable_sanitizers(project_options) +INCLUDE(cmake/Sanitizers.cmake) +ENABLE_SANITIZERS(project_options) # enable doxygen -include(cmake/Doxygen.cmake) -enable_doxygen() +INCLUDE(cmake/Doxygen.cmake) +ENABLE_DOXYGEN() # allow for static analysis options -include(cmake/StaticAnalyzers.cmake) +INCLUDE(cmake/StaticAnalyzers.cmake) -option(BUILD_SHARED_LIBS "Enable compilation of shared libraries" OFF) -option(ENABLE_TESTING "Enable Test Builds" ON) -option(ENABLE_FUZZING "Enable Fuzzing Builds" OFF) +OPTION(BUILD_SHARED_LIBS "Enable compilation of shared libraries" OFF) +OPTION(ENABLE_TESTING "Enable Test Builds" ON) +OPTION(ENABLE_FUZZING "Enable Fuzzing Builds" OFF) # Very basic PCH example -option(ENABLE_PCH "Enable Precompiled Headers" OFF) -if(ENABLE_PCH) - # This sets a global PCH parameter, each project will build its own PCH, which is a good idea if any #define's change - # - # consider breaking this out per project as necessary - target_precompile_headers( - project_options - INTERFACE - - - - ) -endif() +OPTION(ENABLE_PCH "Enable Precompiled Headers" OFF) +IF(ENABLE_PCH) + # This sets a global PCH parameter, each project will build its own PCH, which is a good idea if any #define's change + # + # consider breaking this out per project as necessary + TARGET_PRECOMPILE_HEADERS( + project_options + INTERFACE + + + + ) +ENDIF() # Set up some extra Conan dependencies based on our needs before loading Conan -set(CONAN_EXTRA_REQUIRES "") -set(CONAN_EXTRA_OPTIONS "") +SET(CONAN_EXTRA_REQUIRES "") +SET(CONAN_EXTRA_OPTIONS "") -include(cmake/Conan.cmake) -run_conan() +INCLUDE(cmake/Conan.cmake) +RUN_CONAN() -if(ENABLE_TESTING) - enable_testing() - message("Building Tests. Be sure to check out test/constexpr_tests for constexpr testing") - add_subdirectory(test) -endif() +IF(ENABLE_TESTING) + ENABLE_TESTING() + MESSAGE("Building Tests. Be sure to check out test/constexpr_tests for constexpr testing") + ADD_SUBDIRECTORY(test) +ENDIF() -if(ENABLE_FUZZING) - message("Building Fuzz Tests, using fuzzing sanitizer https://www.llvm.org/docs/LibFuzzer.html") - add_subdirectory(fuzz_test) -endif() - -add_subdirectory(src) +IF(ENABLE_FUZZING) + MESSAGE("Building Fuzz Tests, using fuzzing sanitizer https://www.llvm.org/docs/LibFuzzer.html") + ADD_SUBDIRECTORY(fuzz_test) +ENDIF() +ADD_SUBDIRECTORY(src) diff --git a/fuzz_test/CMakeLists.txt b/fuzz_test/CMakeLists.txt index 5023349..9bef7e1 100644 --- a/fuzz_test/CMakeLists.txt +++ b/fuzz_test/CMakeLists.txt @@ -1,19 +1,19 @@ # A fuzz test runs until it finds an error. This particular one is going to rely on libFuzzer. # -add_executable(fuzz_tester fuzz_tester.cpp) -target_link_libraries( - fuzz_tester - PRIVATE project_options - project_warnings - CONAN_PKG::fmt - -coverage - -fsanitize=fuzzer,undefined,address) -target_compile_options(fuzz_tester PRIVATE -fsanitize=fuzzer,undefined,address) +ADD_EXECUTABLE(fuzz_tester fuzz_tester.cpp) +TARGET_LINK_LIBRARIES( + fuzz_tester + PRIVATE project_options + project_warnings + CONAN_PKG::fmt + -coverage + -fsanitize=fuzzer,undefined,address) +TARGET_COMPILE_OPTIONS(fuzz_tester PRIVATE -fsanitize=fuzzer,undefined,address) # Allow short runs during automated testing to see if something new breaks -set(FUZZ_RUNTIME +SET(FUZZ_RUNTIME 10 CACHE STRING "Number of seconds to run fuzz tests during ctest run") # Default of 10 seconds -add_test(NAME fuzz_tester_run COMMAND fuzz_tester -max_total_time=${FUZZ_RUNTIME}) +ADD_TEST(NAME fuzz_tester_run COMMAND fuzz_tester -max_total_time=${FUZZ_RUNTIME}) diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 739ac52..8a24693 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -1,2 +1,2 @@ -add_subdirectory(catch2) -add_subdirectory(gtest) +ADD_SUBDIRECTORY(catch2) +ADD_SUBDIRECTORY(gtest) diff --git a/test/catch2/CMakeLists.txt b/test/catch2/CMakeLists.txt index 162fd22..f95ae9e 100644 --- a/test/catch2/CMakeLists.txt +++ b/test/catch2/CMakeLists.txt @@ -1,60 +1,60 @@ -include(CTest) -include(Catch) +INCLUDE(CTest) +INCLUDE(Catch) -add_library(catch_main STATIC catch_main.cpp) -target_link_libraries(catch_main PUBLIC CONAN_PKG::catch2) -target_link_libraries(catch_main PRIVATE project_options) +ADD_LIBRARY(catch_main STATIC catch_main.cpp) +TARGET_LINK_LIBRARIES(catch_main PUBLIC CONAN_PKG::catch2) +TARGET_LINK_LIBRARIES(catch_main PRIVATE project_options) -add_executable(catch_tests tests.cpp) -target_link_libraries(catch_tests PRIVATE project_warnings project_options catch_main) +ADD_EXECUTABLE(catch_tests tests.cpp) +TARGET_LINK_LIBRARIES(catch_tests PRIVATE project_warnings project_options catch_main) # automatically discover tests that are defined in catch based test files you can modify the unittests. Set TEST_PREFIX # to whatever you want, or use different for different binaries -catch_discover_tests( - catch_tests - TEST_PREFIX - "catch_unittests." - REPORTER - xml - OUTPUT_DIR - . - OUTPUT_PREFIX - "catch_unittests." - OUTPUT_SUFFIX - .xml) +CATCH_DISCOVER_TESTS( + catch_tests + TEST_PREFIX + "catch_unittests." + REPORTER + xml + OUTPUT_DIR + . + OUTPUT_PREFIX + "catch_unittests." + OUTPUT_SUFFIX + .xml) # Add a file containing a set of constexpr tests -add_executable(catch_constexpr_tests constexpr_tests.cpp) -target_link_libraries(catch_constexpr_tests PRIVATE project_options project_warnings catch_main) +ADD_EXECUTABLE(catch_constexpr_tests constexpr_tests.cpp) +TARGET_LINK_LIBRARIES(catch_constexpr_tests PRIVATE project_options project_warnings catch_main) -catch_discover_tests( - catch_constexpr_tests - TEST_PREFIX - "catch_constexpr." - REPORTER - xml - OUTPUT_DIR - . - OUTPUT_PREFIX - "catch_constexpr." - OUTPUT_SUFFIX - .xml) +CATCH_DISCOVER_TESTS( + catch_constexpr_tests + TEST_PREFIX + "catch_constexpr." + REPORTER + xml + OUTPUT_DIR + . + OUTPUT_PREFIX + "catch_constexpr." + OUTPUT_SUFFIX + .xml) # Disable the constexpr portion of the test, and build again this allows us to have an executable that we can debug when # things go wrong with the constexpr testing -add_executable(catch_relaxed_constexpr_tests constexpr_tests.cpp) -target_link_libraries(catch_relaxed_constexpr_tests PRIVATE project_options project_warnings catch_main) -target_compile_definitions(catch_relaxed_constexpr_tests PRIVATE -DCATCH_CONFIG_RUNTIME_STATIC_REQUIRE) +ADD_EXECUTABLE(catch_relaxed_constexpr_tests constexpr_tests.cpp) +TARGET_LINK_LIBRARIES(catch_relaxed_constexpr_tests PRIVATE project_options project_warnings catch_main) +TARGET_COMPILE_DEFINITIONS(catch_relaxed_constexpr_tests PRIVATE -DCATCH_CONFIG_RUNTIME_STATIC_REQUIRE) -catch_discover_tests( - catch_relaxed_constexpr_tests - TEST_PREFIX - "catch_relaxed_constexpr." - REPORTER - xml - OUTPUT_DIR - . - OUTPUT_PREFIX - "catch_relaxed_constexpr." - OUTPUT_SUFFIX - .xml) +CATCH_DISCOVER_TESTS( + catch_relaxed_constexpr_tests + TEST_PREFIX + "catch_relaxed_constexpr." + REPORTER + xml + OUTPUT_DIR + . + OUTPUT_PREFIX + "catch_relaxed_constexpr." + OUTPUT_SUFFIX + .xml) diff --git a/test/gtest/CMakeLists.txt b/test/gtest/CMakeLists.txt index b54d91d..2e94faf 100644 --- a/test/gtest/CMakeLists.txt +++ b/test/gtest/CMakeLists.txt @@ -1,32 +1,31 @@ -include(CTest) -include(GoogleTest) +INCLUDE(CTest) +INCLUDE(GoogleTest) -add_library(gtest_main STATIC gtest_main.cpp) -target_link_libraries(gtest_main PUBLIC CONAN_PKG::gtest) -target_link_libraries(gtest_main PRIVATE project_options) +ADD_LIBRARY(gtest_main STATIC gtest_main.cpp) +TARGET_LINK_LIBRARIES(gtest_main PUBLIC CONAN_PKG::gtest) +TARGET_LINK_LIBRARIES(gtest_main PRIVATE project_options) -add_executable(gtest_tests tests.cpp) -target_link_libraries(gtest_tests PRIVATE project_warnings project_options gtest_main) +ADD_EXECUTABLE(gtest_tests tests.cpp) +TARGET_LINK_LIBRARIES(gtest_tests PRIVATE project_warnings project_options gtest_main) # automatically discover tests that are defined in gtest based test files you can modify the unittests. Set TEST_PREFIX # to whatever you want, or use different for different binaries -gtest_discover_tests( - gtest_tests - TEST_PREFIX - "gtest_unittests." - XML_OUTPUT_DIR - .) +GTEST_DISCOVER_TESTS( + gtest_tests + TEST_PREFIX + "gtest_unittests." + XML_OUTPUT_DIR + .) # Add a file containing a set of constexpr tests -add_executable(gtest_constexpr_tests constexpr_tests.cpp) -target_link_libraries(gtest_constexpr_tests PRIVATE project_options project_warnings gtest_main) +ADD_EXECUTABLE(gtest_constexpr_tests constexpr_tests.cpp) +TARGET_LINK_LIBRARIES(gtest_constexpr_tests PRIVATE project_options project_warnings gtest_main) -gtest_discover_tests( - gtest_constexpr_tests - TEST_PREFIX - "gtest_constexpr." - XML_OUTPUT_DIR - .) +GTEST_DISCOVER_TESTS( + gtest_constexpr_tests + TEST_PREFIX + "gtest_constexpr." + XML_OUTPUT_DIR + .) # GTest doesn't support switching between constexpr and non-constexpr versions of tests. - From ac9c4c318f22ccad72a1148eadb0172f44fd474c Mon Sep 17 00:00:00 2001 From: Stephan Kantelberg Date: Sat, 21 May 2022 21:52:50 +0200 Subject: [PATCH 4/7] formatted crow --- src/crow/main.cpp | 67 ++++++++++++++++++++--------------------------- 1 file changed, 29 insertions(+), 38 deletions(-) diff --git a/src/crow/main.cpp b/src/crow/main.cpp index 15ff514..3603b05 100644 --- a/src/crow/main.cpp +++ b/src/crow/main.cpp @@ -3,47 +3,38 @@ class a : public crow::returnable { -public: - a() : returnable("text/plain"){}; + public: + a() : returnable("text/plain"){}; - std::string dump() const override - { - return "ABCDF"; - } + std::string dump() const override { return "ABCDF"; } }; int main() { - constexpr uint16_t port = 8080; - std::vector values; - crow::SimpleApp app; - - CROW_ROUTE(app, "/") - ([]() { - return "Hello world"; - }); - - CROW_ROUTE(app, "/json") - ([] { - return crow::json::wvalue({ { "message", "Hello, World!" }, {"message2", "Hello, World.. Again!"} }); - }); - - CROW_ROUTE(app, "/custom") - ([]() { - return a(); - }); - - CROW_ROUTE(app, "/hello/").methods(crow::HTTPMethod::POST)([&values](int count) { - values.push_back(count); - return crow::response(std::to_string(count)); - }); - - CROW_ROUTE(app, "/hello/").methods(crow::HTTPMethod::GET)([&values]() { - crow::json::wvalue returnValue; - returnValue["values"] = values; - return returnValue; - }); - - app.port(port).run(); - return 0; + constexpr uint16_t port = 8080; + std::vector values; + crow::SimpleApp app; + + CROW_ROUTE(app, "/") + ([]() { return "Hello world"; }); + + CROW_ROUTE(app, "/json") + ([]() { return crow::json::wvalue({ { "message", "Hello, World!" }, { "message2", "Hello, World.. Again!" } }); }); + + CROW_ROUTE(app, "/custom") + ([]() { return a(); }); + + CROW_ROUTE(app, "/hello/").methods(crow::HTTPMethod::POST)([&values](int count) { + values.push_back(count); + return crow::response(std::to_string(count)); + }); + + CROW_ROUTE(app, "/hello/").methods(crow::HTTPMethod::GET)([&values]() { + crow::json::wvalue returnValue; + returnValue["values"] = values; + return returnValue; + }); + + app.port(port).run(); + return 0; } From e92d650a23a4f168583bc610593e38c443818092 Mon Sep 17 00:00:00 2001 From: Stephan Kantelberg Date: Sat, 21 May 2022 22:05:59 +0200 Subject: [PATCH 5/7] replaced std::cout with fmt::print --- src/main.cpp | 20 +++++++++++++++----- src/sml/main.cpp | 2 -- templates/version.hpp.in | 2 ++ 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 8661c3b..1929461 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,9 +1,9 @@ -#include -#include -#include #include "include/version.hpp" #include +#include +#include #include +#include static constexpr auto USAGE = R"(Naval Fate. @@ -30,14 +30,24 @@ int main(int argc, const char **argv) Minor {} Patch {} Git Hash {} -)", Version::Major, Version::Minor, Version::Patch, Version::GitHash); +)", + Version::Major, + Version::Minor, + Version::Patch, + Version::GitHash); std::map args = docopt::docopt(USAGE, { std::next(argv), std::next(argv, argc) }, true,// show help if requested "Naval Fate 2.0");// version string - for (auto const &arg : args) { std::cout << arg.first << arg.second << std::endl; } + for (auto const &arg : args) { + fmt::print(R"( +{} {} +)", + arg.first, + arg.second.asString()); + } // Use the default logger (stdout, multi-threaded, colored) spdlog::info("Hello, {}!", "World"); diff --git a/src/sml/main.cpp b/src/sml/main.cpp index 84c1b3c..caacf8a 100644 --- a/src/sml/main.cpp +++ b/src/sml/main.cpp @@ -9,8 +9,6 @@ #include "states.h" #include #include -#include -#include #include using namespace std::chrono_literals; diff --git a/templates/version.hpp.in b/templates/version.hpp.in index 79a0916..7dd0c57 100644 --- a/templates/version.hpp.in +++ b/templates/version.hpp.in @@ -1,4 +1,6 @@ #pragma once +#include +#include struct Version { From c963743769fab0780858d37250239a8fb5260c6d Mon Sep 17 00:00:00 2001 From: Stephan Kantelberg Date: Sat, 21 May 2022 22:35:15 +0200 Subject: [PATCH 6/7] added missing includes --- src/sml/actions.h | 2 ++ src/sml/logger.h | 2 ++ 2 files changed, 4 insertions(+) diff --git a/src/sml/actions.h b/src/sml/actions.h index d9673c3..3527b65 100644 --- a/src/sml/actions.h +++ b/src/sml/actions.h @@ -1,4 +1,6 @@ #pragma once +#include +#include std::chrono::time_point startTime; diff --git a/src/sml/logger.h b/src/sml/logger.h index 1d43eb8..0f8d21f 100644 --- a/src/sml/logger.h +++ b/src/sml/logger.h @@ -1,4 +1,6 @@ #pragma once +#include +#include struct CustomLogger { From 8094129f3076ee97612bd7f1f8113e7a19c59b2d Mon Sep 17 00:00:00 2001 From: Stephan Kantelberg Date: Mon, 30 May 2022 21:51:18 +0200 Subject: [PATCH 7/7] removed WarningAsErrors --- .clang-tidy | 1 - 1 file changed, 1 deletion(-) diff --git a/.clang-tidy b/.clang-tidy index 5978ff9..9948956 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -14,6 +14,5 @@ Checks: "*, -cppcoreguidelines-non-private-member-variables-in-classes, -misc-non-private-member-variables-in-classes, " -WarningsAsErrors: '' HeaderFilterRegex: '' FormatStyle: none