From 30d953b2973ebad57036fe6090ba17214978a277 Mon Sep 17 00:00:00 2001 From: Fabian Ruffy <5960321+fruffy@users.noreply.github.com> Date: Fri, 28 Apr 2023 11:06:28 -0400 Subject: [PATCH] Run linters across test folder. (#3982) * Also lint test. * Run the linter. * Ignore revs for Python. --- .git-blame-ignore-revs | 2 + cmake/Linters.cmake | 3 +- test/gtest/arch_test.cpp | 66 ++-- test/gtest/bitvec_test.cpp | 10 +- test/gtest/call_graph_test.cpp | 10 +- test/gtest/complex_bitwise.cpp | 54 ++- test/gtest/constant_expr_test.cpp | 2 +- test/gtest/cstring.cpp | 23 +- test/gtest/diagnostics.cpp | 51 +-- test/gtest/dumpjson.cpp | 6 +- test/gtest/enumerator_test.cpp | 50 +-- test/gtest/equiv_test.cpp | 14 +- test/gtest/exception_test.cpp | 2 +- test/gtest/expr_uses_test.cpp | 3 +- test/gtest/format_test.cpp | 12 +- test/gtest/gtestp4c.cpp | 7 +- test/gtest/helpers.cpp | 83 +++-- test/gtest/helpers.h | 43 ++- test/gtest/indexed_vector.cpp | 8 +- test/gtest/json_test.cpp | 7 +- test/gtest/load_ir_from_json.cpp | 28 +- test/gtest/midend_test.cpp | 128 +++---- test/gtest/opeq_test.cpp | 2 +- test/gtest/ordered_map.cpp | 8 +- test/gtest/ordered_set.cpp | 12 +- test/gtest/p4runtime.cpp | 554 +++++++++++++++--------------- test/gtest/parser_unroll.cpp | 251 +++++++------- test/gtest/path_test.cpp | 5 +- test/gtest/source_file_test.cpp | 7 +- test/gtest/stringify.cpp | 6 +- test/gtest/transforms.cpp | 14 +- 31 files changed, 688 insertions(+), 783 deletions(-) diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index adcb750e9c..02f98d2388 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -7,3 +7,5 @@ e26a49dbf5749ee92585cec9e95ca781d377ebfd 7a722a3fb8205c57d7e9554fc7c62c2629720d5a # Switched from left to right pointer alignment. f1181a071844f759b618ed3c894cf56e2df1dd05 +# Added a Python formatter. +8947d5ec2c12157d29a2d07ad25cf0245a5792a5 diff --git a/cmake/Linters.cmake b/cmake/Linters.cmake index b81f0a37f3..9baf822e63 100644 --- a/cmake/Linters.cmake +++ b/cmake/Linters.cmake @@ -12,6 +12,8 @@ file( lib/*.h midend/*.cpp midend/*.h + test/*.cpp + test/*.h tools/*.cpp tools/*.h ) @@ -92,7 +94,6 @@ file( tools/*.py ) list(FILTER P4C_PYTHON_LINT_LIST EXCLUDE REGEX "backends/p4tools/submodules") -list(FILTER P4C_PYTHON_LINT_LIST EXCLUDE REGEX "control-plane/p4runtime") list(FILTER P4C_PYTHON_LINT_LIST EXCLUDE REGEX "tools/cpplint.py") add_black_files(${P4C_SOURCE_DIR} "${P4C_PYTHON_LINT_LIST}") diff --git a/test/gtest/arch_test.cpp b/test/gtest/arch_test.cpp index febbc0544c..146cda4935 100644 --- a/test/gtest/arch_test.cpp +++ b/test/gtest/arch_test.cpp @@ -14,24 +14,22 @@ See the License for the specific language governing permissions and limitations under the License. */ -#include "gtest/gtest.h" -#include "ir/ir.h" -#include "helpers.h" -#include "lib/log.h" - #include "frontends/common/parseInput.h" #include "frontends/common/resolveReferences/referenceMap.h" #include "frontends/common/resolveReferences/resolveReferences.h" #include "frontends/p4/createBuiltins.h" #include "frontends/p4/typeChecking/typeChecker.h" #include "frontends/p4/typeMap.h" - +#include "gtest/gtest.h" +#include "helpers.h" +#include "ir/ir.h" +#include "lib/log.h" using namespace P4; namespace Test { -class P4CArchitecture : public P4CTest { }; +class P4CArchitecture : public P4CTest {}; TEST_F(P4CArchitecture, packet_out) { std::string program = P4_SOURCE(R"( @@ -57,10 +55,8 @@ TEST_F(P4CArchitecture, packet_out) { ASSERT_TRUE(pgm != nullptr && ::errorCount() == 0); ReferenceMap refMap; - TypeMap typeMap; - PassManager passes({ - new TypeChecking(&refMap, &typeMap) - }); + TypeMap typeMap; + PassManager passes({new TypeChecking(&refMap, &typeMap)}); pgm = pgm->apply(passes); ASSERT_TRUE(pgm != nullptr && ::errorCount() == 0); @@ -92,10 +88,8 @@ TEST_F(P4CArchitecture, duplicatedDeclarationBug) { if (pgm != nullptr) { ReferenceMap refMap; - TypeMap typeMap; - PassManager passes({ - new TypeChecking(&refMap, &typeMap) - }); + TypeMap typeMap; + PassManager passes({new TypeChecking(&refMap, &typeMap)}); pgm = pgm->apply(passes); } @@ -141,10 +135,8 @@ TEST_F(P4CArchitecture, instantiation) { ASSERT_TRUE(pgm != nullptr && ::errorCount() == 0); ReferenceMap refMap; - TypeMap typeMap; - PassManager passes({ - new TypeChecking(&refMap, &typeMap) - }); + TypeMap typeMap; + PassManager passes({new TypeChecking(&refMap, &typeMap)}); pgm = pgm->apply(passes); ASSERT_TRUE(pgm != nullptr && ::errorCount() == 0); @@ -173,10 +165,8 @@ TEST_F(P4CArchitecture, psa_package_with_body) { if (pgm != nullptr) { ReferenceMap refMap; - TypeMap typeMap; - PassManager passes({ - new TypeChecking(&refMap, &typeMap) - }); + TypeMap typeMap; + PassManager passes({new TypeChecking(&refMap, &typeMap)}); pgm = pgm->apply(passes); } ASSERT_GT(::errorCount(), 0U); @@ -211,10 +201,8 @@ TEST_F(P4CArchitecture, psa_control_in_control) { ASSERT_TRUE(pgm != nullptr && ::errorCount() == 0); ReferenceMap refMap; - TypeMap typeMap; - PassManager passes({ - new TypeChecking(&refMap, &typeMap) - }); + TypeMap typeMap; + PassManager passes({new TypeChecking(&refMap, &typeMap)}); pgm = pgm->apply(passes); ASSERT_TRUE(pgm != nullptr && ::errorCount() == 0); } @@ -237,10 +225,8 @@ TEST_F(P4CArchitecture, psa_clone_as_param_to_package) { ASSERT_TRUE(pgm != nullptr && ::errorCount() == 0); ReferenceMap refMap; - TypeMap typeMap; - PassManager passes({ - new TypeChecking(&refMap, &typeMap) - }); + TypeMap typeMap; + PassManager passes({new TypeChecking(&refMap, &typeMap)}); pgm = pgm->apply(passes); ASSERT_TRUE(pgm != nullptr && ::errorCount() == 0); } @@ -272,10 +258,8 @@ TEST_F(P4CArchitecture, psa_clone_as_param_to_control) { ASSERT_TRUE(pgm != nullptr && ::errorCount() == 0); ReferenceMap refMap; - TypeMap typeMap; - PassManager passes({ - new TypeChecking(&refMap, &typeMap) - }); + TypeMap typeMap; + PassManager passes({new TypeChecking(&refMap, &typeMap)}); pgm = pgm->apply(passes); ASSERT_TRUE(pgm != nullptr && ::errorCount() == 0); } @@ -315,10 +299,8 @@ TEST_F(P4CArchitecture, psa_clone_as_param_to_extern) { ASSERT_TRUE(pgm != nullptr && ::errorCount() == 0); ReferenceMap refMap; - TypeMap typeMap; - PassManager passes({ - new TypeChecking(&refMap, &typeMap) - }); + TypeMap typeMap; + PassManager passes({new TypeChecking(&refMap, &typeMap)}); pgm = pgm->apply(passes); ASSERT_TRUE(pgm != nullptr && ::errorCount() == 0); } @@ -347,10 +329,8 @@ TEST_F(P4CArchitecture, clone_as_extern_method) { ASSERT_TRUE(pgm != nullptr && ::errorCount() == 0); ReferenceMap refMap; - TypeMap typeMap; - PassManager passes({ - new TypeChecking(&refMap, &typeMap) - }); + TypeMap typeMap; + PassManager passes({new TypeChecking(&refMap, &typeMap)}); pgm = pgm->apply(passes); ASSERT_TRUE(pgm != nullptr && ::errorCount() == 0); } diff --git a/test/gtest/bitvec_test.cpp b/test/gtest/bitvec_test.cpp index 25b2cc3ad3..246a97e060 100644 --- a/test/gtest/bitvec_test.cpp +++ b/test/gtest/bitvec_test.cpp @@ -15,9 +15,9 @@ See the License for the specific language governing permissions and limitations under the License. */ +#include "lib/bitvec.h" #include "gtest/gtest.h" -#include "lib/bitvec.h" namespace Test { @@ -31,7 +31,7 @@ TEST(Bitvec, Shift) { #ifdef __SIZEOF_INT128__ TEST(Bitvec, bigval) { - __int128_t val[2] = { 0, 1 }; + __int128_t val[2] = {0, 1}; val[1] <<= 100; bitvec bv(val[1]); EXPECT_EQ(bv.getbit(100), true); @@ -45,12 +45,12 @@ TEST(Bitvec, bigval) { (defined(__clang__) && (__clang_major__ >= 3) && (__clang_minor__ > 8)) bv.setraw(val, 2); EXPECT_EQ(bv.getbit(238), true); -#endif // (defined(__GNUC__) && !defined(__clang__)) || - // (defined(__clang__) && (__clang_major__ >= 3) && (__clang_minor__ > 8)) +#endif // (defined(__GNUC__) && !defined(__clang__)) || + // (defined(__clang__) && (__clang_major__ >= 3) && (__clang_minor__ > 8)) } #else TEST(Bitvec, bigval) { - int64_t val[2] = { 0, 1 }; + int64_t val[2] = {0, 1}; val[1] <<= 60; bitvec bv(val[1]); EXPECT_EQ(bv.getbit(60), true); diff --git a/test/gtest/call_graph_test.cpp b/test/gtest/call_graph_test.cpp index ef0b8a253b..7664d69687 100644 --- a/test/gtest/call_graph_test.cpp +++ b/test/gtest/call_graph_test.cpp @@ -1,5 +1,5 @@ /* -Copyright 2013-present Barefoot Networks, Inc. +Copyright 2013-present Barefoot Networks, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,23 +16,21 @@ limitations under the License. #include -#include "gtest/gtest.h" #include "frontends/p4/callGraph.h" +#include "gtest/gtest.h" namespace Test { template static void sameSet(std::unordered_set &set, std::vector vector) { EXPECT_EQ(vector.size(), set.size()); - for (T v : vector) - EXPECT_NEQ(set.end(), set.find(v)); + for (T v : vector) EXPECT_NEQ(set.end(), set.find(v)); } template static void sameSet(std::set &set, std::vector vector) { EXPECT_EQ(vector.size(), set.size()); - for (T v : vector) - EXPECT_NEQ(set.end(), set.find(v)); + for (T v : vector) EXPECT_NEQ(set.end(), set.find(v)); } TEST(CallGraph, Acyclic) { diff --git a/test/gtest/complex_bitwise.cpp b/test/gtest/complex_bitwise.cpp index 4a55309bef..037643df97 100644 --- a/test/gtest/complex_bitwise.cpp +++ b/test/gtest/complex_bitwise.cpp @@ -1,28 +1,26 @@ -#include #include -#include "gtest/gtest.h" -#include "ir/ir.h" -#include "helpers.h" -#include "lib/log.h" -#include "lib/sourceCodeBuilder.h" +#include #include "frontends/common/parseInput.h" #include "frontends/common/resolveReferences/referenceMap.h" #include "frontends/p4/toP4/toP4.h" #include "frontends/p4/typeChecking/typeChecker.h" #include "frontends/p4/typeMap.h" +#include "gtest/gtest.h" +#include "helpers.h" +#include "ir/ir.h" +#include "lib/log.h" +#include "lib/sourceCodeBuilder.h" #include "midend/simplifyBitwise.h" using namespace P4; - namespace Test { namespace { -std::optional -createSimplifyBitwiseTestCase(const std::string &ingressSource) { +std::optional createSimplifyBitwiseTestCase(const std::string &ingressSource) { std::string source = P4_SOURCE(P4Headers::V1MODEL, R"( header H { @@ -80,7 +78,7 @@ class CountAssignmentStatements : public Inspector { } // namespace -class SimplifyBitwiseTest : public P4CTest { }; +class SimplifyBitwiseTest : public P4CTest {}; TEST_F(SimplifyBitwiseTest, SimpleSplit) { auto test = createSimplifyBitwiseTestCase(P4_SOURCE(R"( @@ -94,12 +92,8 @@ TEST_F(SimplifyBitwiseTest, SimpleSplit) { Util::SourceCodeBuilder builder; ToP4 dump(builder, false); - PassManager quick_midend = { - new TypeChecking(&refMap, &typeMap, true), - new SimplifyBitwise, - &cas, - &dump - }; + PassManager quick_midend = {new TypeChecking(&refMap, &typeMap, true), new SimplifyBitwise, + &cas, &dump}; test->program->apply(quick_midend); EXPECT_EQ(2, cas.as_total()); @@ -123,23 +117,19 @@ TEST_F(SimplifyBitwiseTest, ManySplit) { Util::SourceCodeBuilder builder; ToP4 dump(builder, false); - PassManager quick_midend = { - new TypeChecking(&refMap, &typeMap, true), - new SimplifyBitwise, - &cas, - &dump - }; + PassManager quick_midend = {new TypeChecking(&refMap, &typeMap, true), new SimplifyBitwise, + &cas, &dump}; test->program->apply(quick_midend); EXPECT_EQ(32, cas.as_total()); std::string program_string = builder.toString(); for (int i = 0; i < 32; i += 2) { - std::string value1 = "headers.h.f1[" + std::to_string(i) + ":" + std::to_string(i) - + "] = headers.h.f2[" + std::to_string(i) + ":" - + std::to_string(i) + "]"; - std::string value2 = "headers.h.f1[" + std::to_string(i+1) + ":" + std::to_string(i+1) - + "] = headers.h.f1[" + std::to_string(i+1) + ":" - + std::to_string(i+1) + "]"; + std::string value1 = "headers.h.f1[" + std::to_string(i) + ":" + std::to_string(i) + + "] = headers.h.f2[" + std::to_string(i) + ":" + std::to_string(i) + + "]"; + std::string value2 = "headers.h.f1[" + std::to_string(i + 1) + ":" + std::to_string(i + 1) + + "] = headers.h.f1[" + std::to_string(i + 1) + ":" + + std::to_string(i + 1) + "]"; EXPECT_FALSE(program_string.find(value1) == std::string::npos); EXPECT_FALSE(program_string.find(value2) == std::string::npos); } @@ -156,12 +146,8 @@ TEST_F(SimplifyBitwiseTest, SplitWithZero) { Util::SourceCodeBuilder builder; ToP4 dump(builder, false); - PassManager quick_midend = { - new TypeChecking(&refMap, &typeMap, true), - new SimplifyBitwise, - &cas, - &dump - }; + PassManager quick_midend = {new TypeChecking(&refMap, &typeMap, true), new SimplifyBitwise, + &cas, &dump}; test->program->apply(quick_midend); EXPECT_EQ(3, cas.as_total()); diff --git a/test/gtest/constant_expr_test.cpp b/test/gtest/constant_expr_test.cpp index 0ded409ea6..318b13cc14 100644 --- a/test/gtest/constant_expr_test.cpp +++ b/test/gtest/constant_expr_test.cpp @@ -20,7 +20,7 @@ limitations under the License. namespace Test { -class ConstantExpr : public P4CTest { }; +class ConstantExpr : public P4CTest {}; TEST_F(ConstantExpr, TestInt) { int val = 0x1; diff --git a/test/gtest/cstring.cpp b/test/gtest/cstring.cpp index e4f6f9e7c7..75ab2c97da 100644 --- a/test/gtest/cstring.cpp +++ b/test/gtest/cstring.cpp @@ -14,9 +14,10 @@ See the License for the specific language governing permissions and limitations under the License. */ -#include "gtest/gtest.h" #include "lib/cstring.h" +#include "gtest/gtest.h" + namespace Test { TEST(cstring, construct) { @@ -52,7 +53,7 @@ TEST(cstring, construct) { TEST(cstring, toupper) { cstring c = "simple"; - cstring c1= ""; + cstring c1 = ""; EXPECT_EQ(c.toUpper(), "SIMPLE"); EXPECT_EQ(c1.toUpper(), ""); @@ -81,16 +82,16 @@ TEST(cstring, compare) { EXPECT_FALSE(c == "other"); // NOLINT EXPECT_TRUE(c != "other"); // NOLINT - EXPECT_TRUE(c < "zombie"); // NOLINT - EXPECT_FALSE(c < "awesome"); // NOLINT - EXPECT_TRUE(c <= "zombie"); // NOLINT - EXPECT_FALSE(c <= "awesome"); // NOLINT - EXPECT_TRUE(c >= "awesome"); // NOLINT - EXPECT_TRUE(c > "awesome"); // NOLINT - EXPECT_FALSE(c >= "zombie"); // NOLINT - EXPECT_FALSE(c > "zombie"); // NOLINT + EXPECT_TRUE(c < "zombie"); // NOLINT + EXPECT_FALSE(c < "awesome"); // NOLINT + EXPECT_TRUE(c <= "zombie"); // NOLINT + EXPECT_FALSE(c <= "awesome"); // NOLINT + EXPECT_TRUE(c >= "awesome"); // NOLINT + EXPECT_TRUE(c > "awesome"); // NOLINT + EXPECT_FALSE(c >= "zombie"); // NOLINT + EXPECT_FALSE(c > "zombie"); // NOLINT - const char* ptr = c.c_str(); + const char *ptr = c.c_str(); EXPECT_FALSE(strncmp(ptr, "simple", 7)); } diff --git a/test/gtest/diagnostics.cpp b/test/gtest/diagnostics.cpp index 505a200596..21d70ecc12 100644 --- a/test/gtest/diagnostics.cpp +++ b/test/gtest/diagnostics.cpp @@ -14,14 +14,13 @@ See the License for the specific language governing permissions and limitations under the License. */ +#include #include #include -#include - -#include "gtest/gtest.h" #include "frontends/common/applyOptionsPragmas.h" +#include "gtest/gtest.h" #include "ir/ir.h" #include "test/gtest/helpers.h" @@ -29,8 +28,7 @@ namespace Test { namespace { -std::optional -createP4_16DiagnosticsTestCase(const std::string& pragmaSource) { +std::optional createP4_16DiagnosticsTestCase(const std::string &pragmaSource) { auto source = P4_SOURCE(P4Headers::V1MODEL, R"( %PRAGMA_SOURCE% struct Headers { bit<8> value; } @@ -50,8 +48,7 @@ createP4_16DiagnosticsTestCase(const std::string& pragmaSource) { return FrontendTestCase::create(source); } -std::optional -createP4_14DiagnosticsTestCase(const std::string& pragmaSource) { +std::optional createP4_14DiagnosticsTestCase(const std::string &pragmaSource) { auto source = P4_SOURCE(R"( %PRAGMA_SOURCE% header_type headers_t { fields { value : 8; } } @@ -70,7 +67,7 @@ createP4_14DiagnosticsTestCase(const std::string& pragmaSource) { } // namespace -class Diagnostics : public P4CTest { }; +class Diagnostics : public P4CTest {}; TEST_F(Diagnostics, P4_16_Disable) { auto test = createP4_16DiagnosticsTestCase(P4_SOURCE(R"( @@ -164,10 +161,10 @@ TEST_F(Diagnostics, NestedCompileContexts) { TEST_F(Diagnostics, CompilerOptions) { using CommandLineOptions = P4::IOptionPragmaParser::CommandLineOptions; - auto parseWithCompilerOptions = [](const CommandLineOptions& args) - -> std::optional { - auto& options = GTestContext::get().options(); - options.process(args.size(), const_cast(args.data())); + auto parseWithCompilerOptions = + [](const CommandLineOptions &args) -> std::optional { + auto &options = GTestContext::get().options(); + options.process(args.size(), const_cast(args.data())); return createP4_16DiagnosticsTestCase(P4_SOURCE(R"()")); }; @@ -176,14 +173,14 @@ TEST_F(Diagnostics, CompilerOptions) { { AutoCompileContext autoContext(new GTestContext); - auto test = parseWithCompilerOptions({ "(test)", "--Wdisable" }); + auto test = parseWithCompilerOptions({"(test)", "--Wdisable"}); EXPECT_TRUE(test); EXPECT_EQ(0u, ::diagnosticCount()); } { AutoCompileContext autoContext(new GTestContext); - auto test = parseWithCompilerOptions({ "(test)", "--Wwarn" }); + auto test = parseWithCompilerOptions({"(test)", "--Wwarn"}); EXPECT_TRUE(test); EXPECT_EQ(1u, ::diagnosticCount()); EXPECT_EQ(0u, ::errorCount()); @@ -191,7 +188,7 @@ TEST_F(Diagnostics, CompilerOptions) { { AutoCompileContext autoContext(new GTestContext); - auto test = parseWithCompilerOptions({ "(test)", "--Werror" }); + auto test = parseWithCompilerOptions({"(test)", "--Werror"}); EXPECT_FALSE(test); EXPECT_EQ(1u, ::diagnosticCount()); EXPECT_EQ(1u, ::errorCount()); @@ -202,18 +199,14 @@ TEST_F(Diagnostics, CompilerOptions) { { AutoCompileContext autoContext(new GTestContext); - auto test = parseWithCompilerOptions({ - "(test)", "--Wdisable=uninitialized_out_param" - }); + auto test = parseWithCompilerOptions({"(test)", "--Wdisable=uninitialized_out_param"}); EXPECT_TRUE(test); EXPECT_EQ(0u, ::diagnosticCount()); } { AutoCompileContext autoContext(new GTestContext); - auto test = parseWithCompilerOptions({ - "(test)", "--Wdisable=unknown_diagnostic" - }); + auto test = parseWithCompilerOptions({"(test)", "--Wdisable=unknown_diagnostic"}); EXPECT_TRUE(test); EXPECT_EQ(1u, ::diagnosticCount()); EXPECT_EQ(0u, ::errorCount()); @@ -221,9 +214,7 @@ TEST_F(Diagnostics, CompilerOptions) { { AutoCompileContext autoContext(new GTestContext); - auto test = parseWithCompilerOptions({ - "(test)", "--Wwarn=uninitialized_out_param" - }); + auto test = parseWithCompilerOptions({"(test)", "--Wwarn=uninitialized_out_param"}); EXPECT_TRUE(test); EXPECT_EQ(1u, ::diagnosticCount()); EXPECT_EQ(0u, ::errorCount()); @@ -231,9 +222,7 @@ TEST_F(Diagnostics, CompilerOptions) { { AutoCompileContext autoContext(new GTestContext); - auto test = parseWithCompilerOptions({ - "(test)", "--Werror=uninitialized_out_param" - }); + auto test = parseWithCompilerOptions({"(test)", "--Werror=uninitialized_out_param"}); EXPECT_FALSE(test); EXPECT_EQ(1u, ::diagnosticCount()); EXPECT_EQ(1u, ::errorCount()); @@ -241,9 +230,7 @@ TEST_F(Diagnostics, CompilerOptions) { { AutoCompileContext autoContext(new GTestContext); - auto test = parseWithCompilerOptions({ - "(test)", "--Werror=unknown_diagnostic" - }); + auto test = parseWithCompilerOptions({"(test)", "--Werror=unknown_diagnostic"}); EXPECT_TRUE(test); EXPECT_EQ(1u, ::diagnosticCount()); EXPECT_EQ(0u, ::errorCount()); @@ -254,9 +241,7 @@ TEST_F(Diagnostics, CompilerOptions) { { AutoCompileContext autoContext(new GTestContext); - auto test = parseWithCompilerOptions({ - "(test)", "--Wdisable", "unknown_diagnostic" - }); + auto test = parseWithCompilerOptions({"(test)", "--Wdisable", "unknown_diagnostic"}); EXPECT_TRUE(test); // We expect all warnings to be disabled. If `unknown_diagnostic` was diff --git a/test/gtest/dumpjson.cpp b/test/gtest/dumpjson.cpp index dd9233a4db..c9e0ef1758 100644 --- a/test/gtest/dumpjson.cpp +++ b/test/gtest/dumpjson.cpp @@ -1,5 +1,5 @@ /* -Copyright 2013-present Barefoot Networks, Inc. +Copyright 2013-present Barefoot Networks, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ limitations under the License. TEST(IR, DumpJSON) { auto c = new IR::Constant(2); - IR::Expression* e1 = new IR::Add(Util::SourceInfo(), c, c); + IR::Expression *e1 = new IR::Add(Util::SourceInfo(), c, c); std::stringstream ss, ss2; JSONGenerator(ss) << e1 << std::endl; @@ -32,7 +32,7 @@ TEST(IR, DumpJSON) { JSONLoader loader(ss); std::cout << loader.json; - const IR::Node* e2 = nullptr; + const IR::Node *e2 = nullptr; loader >> e2; JSONGenerator(std::cout) << e2 << std::endl; } diff --git a/test/gtest/enumerator_test.cpp b/test/gtest/enumerator_test.cpp index 63ab9fd404..288527245f 100644 --- a/test/gtest/enumerator_test.cpp +++ b/test/gtest/enumerator_test.cpp @@ -14,11 +14,12 @@ See the License for the specific language governing permissions and limitations under the License. */ +#include "lib/enumerator.h" + #include #include #include "gtest/gtest.h" -#include "lib/enumerator.h" namespace Util { @@ -35,11 +36,11 @@ class UtilEnumerator : public ::testing::Test { explicit B(int b) : A(b) {} }; - std::vector vec{ 1, 2, 3 }; + std::vector vec{1, 2, 3}; }; TEST_F(UtilEnumerator, Simple) { - Enumerator* enumerator = Util::Enumerator::createEnumerator(vec); + Enumerator *enumerator = Util::Enumerator::createEnumerator(vec); bool more = enumerator->moveNext(); EXPECT_TRUE(more); @@ -73,19 +74,18 @@ TEST_F(UtilEnumerator, Simple) { } TEST_F(UtilEnumerator, Range) { - Enumerator* enumerator = Util::Enumerator::createEnumerator(vec); + Enumerator *enumerator = Util::Enumerator::createEnumerator(vec); int sum = 0; - for (auto a : *enumerator) - sum += a; + for (auto a : *enumerator) sum += a; EXPECT_EQ(6, sum); } TEST_F(UtilEnumerator, Linq) { // where - Enumerator* enumerator = Util::Enumerator::createEnumerator(vec); + Enumerator *enumerator = Util::Enumerator::createEnumerator(vec); auto isEven = [](int x) { return x % 2 == 0; }; - Enumerator* even = enumerator->where(isEven); + Enumerator *even = enumerator->where(isEven); bool more = even->moveNext(); EXPECT_TRUE(more); @@ -99,7 +99,7 @@ TEST_F(UtilEnumerator, Linq) { /// map { enumerator->reset(); - std::function increment = [](int x) { return x+1; }; + std::function increment = [](int x) { return x + 1; }; auto inc = enumerator->map(increment); more = inc->moveNext(); EXPECT_TRUE(more); @@ -135,17 +135,17 @@ TEST_F(UtilEnumerator, Linq) { { //// concat - Enumerator* col1 = Util::Enumerator::createEnumerator(vec); - Enumerator* col2 = Util::Enumerator::createEnumerator(vec); - Enumerator* col3 = Util::Enumerator::createEnumerator(vec); - std::vector*> all; + Enumerator *col1 = Util::Enumerator::createEnumerator(vec); + Enumerator *col2 = Util::Enumerator::createEnumerator(vec); + Enumerator *col3 = Util::Enumerator::createEnumerator(vec); + std::vector *> all; all.push_back(col1); all.push_back(col2); all.push_back(col3); - Enumerator*>* allEnums = - Enumerator*>::createEnumerator(all); - Enumerator* concat = Enumerator::concatAll(allEnums); + Enumerator *> *allEnums = + Enumerator *>::createEnumerator(all); + Enumerator *concat = Enumerator::concatAll(allEnums); uint64_t count = concat->count(); EXPECT_EQ(9u, count); @@ -153,8 +153,8 @@ TEST_F(UtilEnumerator, Linq) { count = concat->count(); EXPECT_EQ(9u, count); - Enumerator* cc1 = Util::Enumerator::createEnumerator(vec); - Enumerator* cc2 = Util::Enumerator::createEnumerator(vec); + Enumerator *cc1 = Util::Enumerator::createEnumerator(vec); + Enumerator *cc2 = Util::Enumerator::createEnumerator(vec); cc1 = cc1->concat(cc2); count = cc1->count(); EXPECT_EQ(6u, count); @@ -162,15 +162,15 @@ TEST_F(UtilEnumerator, Linq) { { // as - std::vector bs; + std::vector bs; bs.push_back(new B(1)); bs.push_back(new B(2)); - Enumerator *benum = Enumerator::createEnumerator(bs); - Enumerator *aenum = benum->as(); + Enumerator *benum = Enumerator::createEnumerator(bs); + Enumerator *aenum = benum->as(); more = aenum->moveNext(); EXPECT_TRUE(more); - A* a = aenum->getCurrent(); + A *a = aenum->getCurrent(); EXPECT_EQ(1, a->a); more = aenum->moveNext(); @@ -184,20 +184,20 @@ TEST_F(UtilEnumerator, Linq) { // first & co. { - Enumerator* vi = Util::Enumerator::createEnumerator(vec); + Enumerator *vi = Util::Enumerator::createEnumerator(vec); EXPECT_EQ(1, vi->next()); EXPECT_EQ(2, vi->nextOrDefault()); EXPECT_EQ(3, vi->nextOrDefault()); EXPECT_EQ(0, vi->nextOrDefault()); - Enumerator* e = Util::Enumerator::emptyEnumerator(); + Enumerator *e = Util::Enumerator::emptyEnumerator(); EXPECT_THROW(e->next(), std::logic_error); } { std::vector s; s.push_back(5); - Enumerator* e = Util::Enumerator::createEnumerator(s); + Enumerator *e = Util::Enumerator::createEnumerator(s); EXPECT_EQ(5, e->single()); EXPECT_THROW(e->single(), std::logic_error); } diff --git a/test/gtest/equiv_test.cpp b/test/gtest/equiv_test.cpp index f93534202a..851ffaf5d9 100644 --- a/test/gtest/equiv_test.cpp +++ b/test/gtest/equiv_test.cpp @@ -1,5 +1,5 @@ /* -Copyright 2013-present Barefoot Networks, Inc. +Copyright 2013-present Barefoot Networks, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -43,16 +43,16 @@ TEST(IR, Equiv) { EXPECT_FALSE(d1m->equiv(*em)); EXPECT_FALSE(d1m->equiv(*d1f)); - auto *call1 = new IR::MethodCallExpression(d1m, { a1, d1 }); - auto *call2 = new IR::MethodCallExpression(d2m, { a2, d2 }); - auto *call3 = new IR::MethodCallExpression(d1m, { b, d1 }); + auto *call1 = new IR::MethodCallExpression(d1m, {a1, d1}); + auto *call2 = new IR::MethodCallExpression(d2m, {a2, d2}); + auto *call3 = new IR::MethodCallExpression(d1m, {b, d1}); EXPECT_TRUE(call1->equiv(*call2)); EXPECT_FALSE(call1->equiv(*call3)); - auto *list1 = new IR::ListExpression({ a1, b, d1 }); - auto *list2 = new IR::ListExpression({ a1, b, d2 }); - auto *list3 = new IR::ListExpression({ a1, b, e }); + auto *list1 = new IR::ListExpression({a1, b, d1}); + auto *list2 = new IR::ListExpression({a1, b, d2}); + auto *list3 = new IR::ListExpression({a1, b, e}); EXPECT_TRUE(list1->equiv(*list2)); EXPECT_FALSE(list1->equiv(*list3)); diff --git a/test/gtest/exception_test.cpp b/test/gtest/exception_test.cpp index 2f665af33a..1e1b9c9b16 100644 --- a/test/gtest/exception_test.cpp +++ b/test/gtest/exception_test.cpp @@ -29,7 +29,7 @@ TEST(UtilException, Messages) { } catch (std::exception &ex) { cstring err(ex.what()); cstring redir_msg("Compiler Bug:\ntest\n"); - cstring no_redir_msg = cstring(ANSI_RED) + "Compiler Bug" + ANSI_CLR +":\ntest\n"; + cstring no_redir_msg = cstring(ANSI_RED) + "Compiler Bug" + ANSI_CLR + ":\ntest\n"; // The error message might or might not be colorized based on if the test are redirected // or not, to make sure both options are valid an array is used. bool is_content_correct = (err == redir_msg) || (err == no_redir_msg); diff --git a/test/gtest/expr_uses_test.cpp b/test/gtest/expr_uses_test.cpp index 577360e3d6..580a51c96c 100644 --- a/test/gtest/expr_uses_test.cpp +++ b/test/gtest/expr_uses_test.cpp @@ -14,11 +14,12 @@ See the License for the specific language governing permissions and limitations under the License. */ +#include "midend/expr_uses.h" + #include "gtest/gtest.h" #include "ir/ir.h" #include "ir/visitor.h" #include "lib/exceptions.h" -#include "midend/expr_uses.h" TEST(expr_uses, expr_uses) { auto obj1 = new IR::PathExpression("obj1"); diff --git a/test/gtest/format_test.cpp b/test/gtest/format_test.cpp index 5a9f86283f..692d4114e3 100644 --- a/test/gtest/format_test.cpp +++ b/test/gtest/format_test.cpp @@ -1,5 +1,5 @@ /* -Copyright 2013-present Barefoot Networks, Inc. +Copyright 2013-present Barefoot Networks, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -15,14 +15,14 @@ limitations under the License. */ #include "gtest/gtest.h" -#include "lib/error.h" #include "lib/cstring.h" +#include "lib/error.h" #include "lib/stringify.h" namespace Util { TEST(Util, Format) { - auto& context = BaseCompileContext::get(); + auto &context = BaseCompileContext::get(); cstring message = context.errorReporter().format_message("%1%", 5u); EXPECT_EQ("5\n", message); @@ -36,10 +36,8 @@ TEST(Util, Format) { int a, b, c; cstring toString() const { - return cstring("(") + - Util::toString(this->a) + "," + - Util::toString(this->b) + "," + - Util::toString(this->c) + ")"; + return cstring("(") + Util::toString(this->a) + "," + Util::toString(this->b) + "," + + Util::toString(this->c) + ")"; } }; diff --git a/test/gtest/gtestp4c.cpp b/test/gtest/gtestp4c.cpp index 0a8a9ddf76..0f8590205c 100644 --- a/test/gtest/gtestp4c.cpp +++ b/test/gtest/gtestp4c.cpp @@ -1,5 +1,5 @@ /* -Copyright 2013-present Barefoot Networks, Inc. +Copyright 2013-present Barefoot Networks, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,9 +14,8 @@ See the License for the specific language governing permissions and limitations under the License. */ -#include "gtest/gtest.h" - #include "frontends/common/options.h" +#include "gtest/gtest.h" #include "helpers.h" #include "lib/log.h" @@ -28,7 +27,7 @@ int main(int argc, char **argv) { if (diagnosticCount() > 0) return -1; // Initialize the global test environment. - (void) P4CTestEnvironment::get(); + (void)P4CTestEnvironment::get(); return RUN_ALL_TESTS(); } diff --git a/test/gtest/helpers.cpp b/test/gtest/helpers.cpp index dc6e94d578..d743ab0635 100644 --- a/test/gtest/helpers.cpp +++ b/test/gtest/helpers.cpp @@ -14,16 +14,16 @@ See the License for the specific language governing permissions and limitations under the License. */ +#include "test/gtest/helpers.h" + +#include + #include #include -#include #include // IWYU pragma: keep +#include #include -#include - -#include "helpers.h" - #include "frontends/common/applyOptionsPragmas.h" #include "frontends/common/parseInput.h" #include "frontends/p4/frontend.h" @@ -31,13 +31,14 @@ limitations under the License. namespace detail { -std::string makeP4Source(const char* file, unsigned line, - P4Headers headers, const char* rawSource) { +std::string makeP4Source(const char *file, unsigned line, P4Headers headers, + const char *rawSource) { std::string headers_string; // Prepend any requested headers. switch (headers) { - case P4Headers::NONE: break; + case P4Headers::NONE: + break; case P4Headers::CORE: headers_string = P4CTestEnvironment::get()->coreP4(); break; @@ -45,15 +46,15 @@ std::string makeP4Source(const char* file, unsigned line, headers_string = P4CTestEnvironment::get()->v1Model(); break; case P4Headers::PSA: - headers_string = P4CTestEnvironment::get()->coreP4() - + P4CTestEnvironment::get()->psaP4(); + headers_string = + P4CTestEnvironment::get()->coreP4() + P4CTestEnvironment::get()->psaP4(); break; } return makeP4Source(file, line, headers_string.c_str(), rawSource); } -std::string makeP4Source(const char* file, unsigned line, - const char* headers, const char* rawSource) { +std::string makeP4Source(const char *file, unsigned line, const char *headers, + const char *rawSource) { std::stringstream source; // Prepend any requested headers. @@ -74,25 +75,25 @@ std::string makeP4Source(const char* file, unsigned line, // to subtract the number of lines in the program to get the *first* line of // the macro, which is what we need to use in #line to get the correct // mapping to the unit test source. - source << "#line " << (line - lineCount) << " \"" << file << "\"" << std::endl; + source << "#line " << (line - lineCount) << " \"" << file << "\"" << std::endl; source << rawSource; return source.str(); } -std::string makeP4Source(const char* file, unsigned line, const char* rawSource) { +std::string makeP4Source(const char *file, unsigned line, const char *rawSource) { return makeP4Source(file, line, P4Headers::NONE, rawSource); } } // namespace detail -/* static */ P4CTestEnvironment* P4CTestEnvironment::get() { - static P4CTestEnvironment* instance = new P4CTestEnvironment; +/* static */ P4CTestEnvironment *P4CTestEnvironment::get() { + static P4CTestEnvironment *instance = new P4CTestEnvironment; return instance; } -std::string P4CTestEnvironment::readHeader(const char* filename, bool preprocess, - const char *macro, int macro_val) { +std::string P4CTestEnvironment::readHeader(const char *filename, bool preprocess, const char *macro, + int macro_val) { if (preprocess) { std::stringstream cmd; #ifdef __clang__ @@ -101,12 +102,10 @@ std::string P4CTestEnvironment::readHeader(const char* filename, bool preprocess cmd << "cpp"; #endif cmd << " -C -undef -nostdinc -Ip4include"; - if (macro) - cmd << " -D" << macro << "=" << macro_val; - cmd << " " << filename; - FILE* in = popen(cmd.str().c_str(), "r"); - if (in == nullptr) - throw std::runtime_error(std::string("Couldn't invoke preprocessor")); + if (macro) cmd << " -D" << macro << "=" << macro_val; + cmd << " " << filename; + FILE *in = popen(cmd.str().c_str(), "r"); + if (in == nullptr) throw std::runtime_error(std::string("Couldn't invoke preprocessor")); std::stringstream buffer; char string[100]; while (fgets(string, sizeof(string), in)) buffer << string; @@ -114,23 +113,21 @@ std::string P4CTestEnvironment::readHeader(const char* filename, bool preprocess if (WIFEXITED(exitCode) && WEXITSTATUS(exitCode) == 4) { throw std::runtime_error(std::string("Couldn't find standard header ") + filename); } else if (exitCode != 0) { - throw std::runtime_error(std::string("Couldn't preprocess standard header ") - + filename); + throw std::runtime_error(std::string("Couldn't preprocess standard header ") + + filename); } return buffer.str(); } else { std::ifstream input(filename); if (!input.good()) { - throw std::runtime_error(std::string("Couldn't read standard header ") - + filename); + throw std::runtime_error(std::string("Couldn't read standard header ") + filename); } // Initialize a buffer with a #line preprocessor directive. This // ensures that any errors we encounter in this header will // reference the correct file and line. std::stringstream buffer; - if (macro) - buffer << "#define " << macro << " " << macro_val << std::endl; + if (macro) buffer << "#define " << macro << " " << macro_val << std::endl; buffer << "#line 1 \"" << filename << "\"" << std::endl; // Read the header into the buffer and return it. @@ -153,28 +150,28 @@ P4CTestEnvironment::P4CTestEnvironment() { namespace Test { -/* static */ std::optional -FrontendTestCase::create(const std::string& source, - CompilerOptions::FrontendVersion langVersion - /* = CompilerOptions::FrontendVersion::P4_16 */, - P4::ParseAnnotations parseAnnotations - /* = P4::ParseAnnotations() */) { - auto* program = P4::parseP4String(source, langVersion); +/* static */ std::optional FrontendTestCase::create( + const std::string &source, + CompilerOptions::FrontendVersion langVersion + /* = CompilerOptions::FrontendVersion::P4_16 */, + P4::ParseAnnotations parseAnnotations + /* = P4::ParseAnnotations() */) { + auto *program = P4::parseP4String(source, langVersion); if (program == nullptr) { std::cerr << "Couldn't parse test case source" << std::endl; return std::nullopt; } if (::diagnosticCount() > 0) { - std::cerr << "Encountered " << ::diagnosticCount() - << " errors while parsing test case" << std::endl; + std::cerr << "Encountered " << ::diagnosticCount() << " errors while parsing test case" + << std::endl; return std::nullopt; } P4::P4COptionPragmaParser optionsPragmaParser; program->apply(P4::ApplyOptionsPragmas(optionsPragmaParser)); if (::errorCount() > 0) { - std::cerr << "Encountered " << ::errorCount() - << " errors while collecting options pragmas" << std::endl; + std::cerr << "Encountered " << ::errorCount() << " errors while collecting options pragmas" + << std::endl; return std::nullopt; } @@ -186,8 +183,8 @@ FrontendTestCase::create(const std::string& source, return std::nullopt; } if (::errorCount() > 0) { - std::cerr << "Encountered " << ::errorCount() - << " errors while executing frontend" << std::endl; + std::cerr << "Encountered " << ::errorCount() << " errors while executing frontend" + << std::endl; return std::nullopt; } diff --git a/test/gtest/helpers.h b/test/gtest/helpers.h index 2b95ac35e4..edc40d39e8 100644 --- a/test/gtest/helpers.h +++ b/test/gtest/helpers.h @@ -17,9 +17,8 @@ limitations under the License. #ifndef TEST_GTEST_HELPERS_H_ #define TEST_GTEST_HELPERS_H_ -#include - #include +#include #include "frontends/common/options.h" #include "frontends/p4/parseAnnotations.h" @@ -31,10 +30,10 @@ class P4Program; /// Specifies which standard headers should be included by a GTest. enum class P4Headers { - NONE, // No headers. - CORE, // Just core.p4. + NONE, // No headers. + CORE, // Just core.p4. V1MODEL, // Both core.p4 and v1model.p4. - PSA // Both core.p4 and psa.p4 + PSA // Both core.p4 and psa.p4 }; namespace detail { @@ -52,14 +51,13 @@ namespace detail { * find it convenient to specify this as a raw string. * @return the transformed P4 program. */ -std::string makeP4Source(const char* file, unsigned line, - const char* headers, const char* rawSource); -std::string makeP4Source(const char* file, unsigned line, - P4Headers headers, const char* rawSource); +std::string makeP4Source(const char *file, unsigned line, const char *headers, + const char *rawSource); +std::string makeP4Source(const char *file, unsigned line, P4Headers headers, const char *rawSource); /// An overload of makeP4Source which doesn't prepend any headers; equivalent to /// `makeP4Source(file, line, P4Headers::NONE, rawSource);`. -std::string makeP4Source(const char* file, unsigned line, const char* rawSource); +std::string makeP4Source(const char *file, unsigned line, const char *rawSource); } // namespace detail @@ -75,19 +73,19 @@ class P4CTestEnvironment { // same, resulting in a double delete that's not easy to resolve cleanly. public: /// @return the global instance of P4CTestEnvironment. - static P4CTestEnvironment* get(); + static P4CTestEnvironment *get(); - static std::string readHeader(const char* filename, bool preprocess = false, + static std::string readHeader(const char *filename, bool preprocess = false, const char *macro = nullptr, int macro_val = 1); /// @return a string containing the "core.p4" P4 standard header. - const std::string& coreP4() const { return _coreP4; } + const std::string &coreP4() const { return _coreP4; } /// @return a string containing the "v1model.p4" P4 standard header. - const std::string& v1Model() const { return _v1Model; } + const std::string &v1Model() const { return _v1Model; } /// @return a string containing the "psa.p4" P4 standard header. - const std::string& psaP4() const { return _psaP4; } + const std::string &psaP4() const { return _psaP4; } private: P4CTestEnvironment(); @@ -105,7 +103,7 @@ namespace Test { /// context for the test to run in. class P4CTest : public ::testing::Test { public: - P4CTest() : autoGTestContext(new GTestContext(GTestContext::get())) { } + P4CTest() : autoGTestContext(new GTestContext(GTestContext::get())) {} private: AutoCompileContext autoGTestContext; @@ -116,18 +114,17 @@ struct FrontendTestCase { CompilerOptions::FrontendVersion::P4_16; /// Create a test case that only requires the frontend to run. - static std::optional - create(const std::string& source, - CompilerOptions::FrontendVersion langVersion = defaultVersion, - P4::ParseAnnotations parseAnnotations = P4::ParseAnnotations()); + static std::optional create( + const std::string &source, CompilerOptions::FrontendVersion langVersion = defaultVersion, + P4::ParseAnnotations parseAnnotations = P4::ParseAnnotations()); - static std::optional - create(const std::string& source, P4::ParseAnnotations parseAnnotations) { + static std::optional create(const std::string &source, + P4::ParseAnnotations parseAnnotations) { return create(source, defaultVersion, parseAnnotations); } /// The output of the frontend. - const IR::P4Program* program; + const IR::P4Program *program; }; } // namespace Test diff --git a/test/gtest/indexed_vector.cpp b/test/gtest/indexed_vector.cpp index b8339345c2..7dc013ca73 100644 --- a/test/gtest/indexed_vector.cpp +++ b/test/gtest/indexed_vector.cpp @@ -9,8 +9,8 @@ using namespace IR; using TestVector = IndexedVector; -const Type* testType() { return Type_Bits::get(8); } -StructField* testItem(cstring val) { return new StructField(ID(val), testType()); } +const Type *testType() { return Type_Bits::get(8); } +StructField *testItem(cstring val) { return new StructField(ID(val), testType()); } TEST(IndexedVector, basics) { TestVector vec; @@ -28,7 +28,7 @@ TEST(IndexedVector, basics) { EXPECT_EQ(vec[1]->name.name, "bar"); cstring check = "foo"; - for (auto* dec : vec) { + for (auto *dec : vec) { EXPECT_EQ(dec->name.name, check); check = "bar"; } @@ -81,7 +81,7 @@ TEST(IndexedVector, ilist_ctor) { } TEST(IndexedVector, save_vector_ctor) { - TestVector vec(safe_vector{testItem("foo"), testItem("bar")}); + TestVector vec(safe_vector{testItem("foo"), testItem("bar")}); EXPECT_EQ(vec.size(), 2u); EXPECT_EQ(vec[0]->name.name, "foo"); EXPECT_EQ(vec[1]->name.name, "bar"); diff --git a/test/gtest/json_test.cpp b/test/gtest/json_test.cpp index 899f9c3b41..0987a5aea5 100644 --- a/test/gtest/json_test.cpp +++ b/test/gtest/json_test.cpp @@ -1,5 +1,5 @@ /* -Copyright 2013-present Barefoot Networks, Inc. +Copyright 2013-present Barefoot Networks, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,10 +14,11 @@ See the License for the specific language governing permissions and limitations under the License. */ +#include "lib/json.h" + #include #include "gtest/gtest.h" -#include "lib/json.h" namespace Util { @@ -29,7 +30,7 @@ static cstring getNumStringRepr(T v) { } TEST(Util, Json) { - IJson* value; + IJson *value; value = new JsonValue(true); EXPECT_EQ("true", value->toString()); value = new JsonValue(); diff --git a/test/gtest/load_ir_from_json.cpp b/test/gtest/load_ir_from_json.cpp index 907e81bd78..91e913bc68 100644 --- a/test/gtest/load_ir_from_json.cpp +++ b/test/gtest/load_ir_from_json.cpp @@ -14,18 +14,19 @@ See the License for the specific language governing permissions and limitations under the License. */ -#include #include #include -#include -#include +#include + +#include #include +#include +#include #include -#include #include "gtest/gtest.h" -#include "ir/ir.h" #include "helpers.h" +#include "ir/ir.h" #include "lib/log.h" using namespace P4; @@ -33,19 +34,22 @@ using namespace std; namespace Test { -class FromJSONTest : public P4CTest { }; +class FromJSONTest : public P4CTest {}; TEST_F(FromJSONTest, load_ir_from_json) { - int exitCode = system("./p4c-bm2-ss -o outputTO.json ../test/test_fromJSON.p4 " - "--toJSON jsonFile.json"); + int exitCode = system( + "./p4c-bm2-ss -o outputTO.json ../test/test_fromJSON.p4 " + "--toJSON jsonFile.json"); ASSERT_FALSE(exitCode); exitCode = system("./p4c-bm2-ss -o outputFROM.json --fromJSON jsonFile.json"); ASSERT_FALSE(exitCode); - exitCode = system("grep -v program outputTO.json > outputTO.json.tmp; " - "mv outputTO.json.tmp outputTO.json"); + exitCode = system( + "grep -v program outputTO.json > outputTO.json.tmp; " + "mv outputTO.json.tmp outputTO.json"); ASSERT_FALSE(exitCode); - exitCode = system("grep -v program outputFROM.json > outputFROM.json.tmp; " - "mv outputFROM.json.tmp outputFROM.json"); + exitCode = system( + "grep -v program outputFROM.json > outputFROM.json.tmp; " + "mv outputFROM.json.tmp outputFROM.json"); ASSERT_FALSE(exitCode); exitCode = system("diff outputTO.json outputFROM.json"); ASSERT_FALSE(exitCode); diff --git a/test/gtest/midend_test.cpp b/test/gtest/midend_test.cpp index 466b617daa..9b525541e3 100644 --- a/test/gtest/midend_test.cpp +++ b/test/gtest/midend_test.cpp @@ -14,16 +14,15 @@ See the License for the specific language governing permissions and limitations under the License. */ -#include "gtest/gtest.h" -#include "ir/ir.h" -#include "helpers.h" -#include "lib/log.h" - #include "frontends/common/parseInput.h" #include "frontends/common/resolveReferences/referenceMap.h" #include "frontends/common/resolveReferences/resolveReferences.h" #include "frontends/p4/typeChecking/typeChecker.h" #include "frontends/p4/typeMap.h" +#include "gtest/gtest.h" +#include "helpers.h" +#include "ir/ir.h" +#include "lib/log.h" #include "midend/convertEnums.h" #include "midend/replaceSelectRange.h" @@ -34,17 +33,13 @@ namespace Test { namespace { class EnumOn32Bits : public ChooseEnumRepresentation { - bool convert(const IR::Type_Enum*) const override { - return true; - } - unsigned enumSize(unsigned) const override { - return 32; - } + bool convert(const IR::Type_Enum *) const override { return true; } + unsigned enumSize(unsigned) const override { return 32; } }; } // namespace -class P4CMidend : public P4CTest { }; +class P4CMidend : public P4CTest {}; // test various way of using enum TEST_F(P4CMidend, convertEnums_pass) { @@ -59,12 +54,10 @@ TEST_F(P4CMidend, convertEnums_pass) { // Example to enable logging in source // Log::addDebugSpec("convertEnums:0"); - ReferenceMap refMap; - TypeMap typeMap; + ReferenceMap refMap; + TypeMap typeMap; auto convertEnums = new P4::ConvertEnums(&refMap, &typeMap, new EnumOn32Bits()); - PassManager passes = { - convertEnums - }; + PassManager passes = {convertEnums}; pgm = pgm->apply(passes); ASSERT_TRUE(pgm != nullptr && errorCount() == 0); } @@ -78,12 +71,10 @@ TEST_F(P4CMidend, convertEnums_used_before_declare) { auto pgm = P4::parseP4String(program, CompilerOptions::FrontendVersion::P4_16); ASSERT_TRUE(pgm && ::errorCount() == 0); - ReferenceMap refMap; - TypeMap typeMap; + ReferenceMap refMap; + TypeMap typeMap; auto convertEnums = new P4::ConvertEnums(&refMap, &typeMap, new EnumOn32Bits()); - PassManager passes = { - convertEnums - }; + PassManager passes = {convertEnums}; pgm = pgm->apply(passes); // use enum before declaration should fail ASSERT_GT(::errorCount(), 0U); @@ -98,13 +89,11 @@ TEST_F(P4CMidend, getEnumMapping) { auto pgm = P4::parseP4String(program, CompilerOptions::FrontendVersion::P4_16); ASSERT_TRUE(pgm != nullptr); - ReferenceMap refMap; - TypeMap typeMap; + ReferenceMap refMap; + TypeMap typeMap; P4::ConvertEnums::EnumMapping enumMap; auto convertEnums = new P4::ConvertEnums(&refMap, &typeMap, new EnumOn32Bits()); - PassManager passes_ = { - convertEnums - }; + PassManager passes_ = {convertEnums}; auto result = pgm->apply(passes_); ASSERT_TRUE(result != nullptr && ::errorCount() == 0); @@ -117,12 +106,12 @@ class CollectRangesAndMasks : public Inspector { std::vector ranges; std::vector masks; - bool preorder(const IR::Range* r) override { + bool preorder(const IR::Range *r) override { ranges.emplace_back(r); return true; } - bool preorder(const IR::Mask* m) override { + bool preorder(const IR::Mask *m) override { masks.emplace_back(m); return true; } @@ -133,17 +122,16 @@ using Mask = std::pair; // note: the callback is used so that SCOPED_TRACE is able to add additional // information visible even if the tests in the callback fail -template -static void -testReplaceSelectRange(std::vector ranges, ExtraTests extraTests) -{ +template +static void testReplaceSelectRange(std::vector ranges, ExtraTests extraTests) { static_assert(std::is_same::value || std::is_same::value, "only uint16_t and int16_t can be used as template argument " "of testReplaceSelectRange"); std::stringstream code; code << R"( struct bs { - )" << (std::is_signed::value ? "int" : "bit") << R"(<16> x; + )" + << (std::is_signed::value ? "int" : "bit") << R"(<16> x; } parser p(in bs b, out bool matches) @@ -167,16 +155,14 @@ testReplaceSelectRange(std::vector ranges, ExtraTests extraTests) auto pgm = P4::parseP4String(program, CompilerOptions::FrontendVersion::P4_16); ASSERT_TRUE(pgm != nullptr); - ReferenceMap refMap; - TypeMap typeMap; + ReferenceMap refMap; + TypeMap typeMap; - PassManager passes_ = { - new P4::ResolveReferences(&refMap), - new P4::TypeInference(&refMap, &typeMap, false), - // properly set types for compound expressions - new P4::TypeChecking(&refMap, &typeMap, true), - new P4::ReplaceSelectRange(&refMap, &typeMap) - }; + PassManager passes_ = {new P4::ResolveReferences(&refMap), + new P4::TypeInference(&refMap, &typeMap, false), + // properly set types for compound expressions + new P4::TypeChecking(&refMap, &typeMap, true), + new P4::ReplaceSelectRange(&refMap, &typeMap)}; auto result = pgm->apply(passes_); ASSERT_TRUE(result != nullptr); ASSERT_EQ(::errorCount(), 0u); @@ -213,7 +199,6 @@ testReplaceSelectRange(std::vector ranges, ExtraTests extraTests) extraTests(collect); } - // test that 0..X ranges are replaced efficienlty by masks TEST_F(P4CMidend, replaceSelectRangeZero1) { testReplaceSelectRange({{0, 255}}, [](CollectRangesAndMasks collect) { @@ -248,69 +233,58 @@ TEST_F(P4CMidend, replaceSelectRangeZero4) { } TEST_F(P4CMidend, replaceSelectRangeZero5) { - testReplaceSelectRange({{0, 1235}}, [](CollectRangesAndMasks collect) { - ASSERT_EQ(collect.masks.size(), 5u); - }); + testReplaceSelectRange( + {{0, 1235}}, [](CollectRangesAndMasks collect) { ASSERT_EQ(collect.masks.size(), 5u); }); } TEST_F(P4CMidend, replaceSelectRangeZero6) { - testReplaceSelectRange({{0, 65535}}, [](CollectRangesAndMasks collect) { - ASSERT_EQ(collect.masks.size(), 1u); - }); + testReplaceSelectRange( + {{0, 65535}}, [](CollectRangesAndMasks collect) { ASSERT_EQ(collect.masks.size(), 1u); }); } TEST_F(P4CMidend, replaceSelectRangeZero7) { - testReplaceSelectRange({{0, 0}}, [](CollectRangesAndMasks collect) { - ASSERT_EQ(collect.masks.size(), 1u); - }); + testReplaceSelectRange( + {{0, 0}}, [](CollectRangesAndMasks collect) { ASSERT_EQ(collect.masks.size(), 1u); }); } TEST_F(P4CMidend, replaceSelectRangeZero8) { - testReplaceSelectRange({{0, 1}}, [](CollectRangesAndMasks collect) { - ASSERT_EQ(collect.masks.size(), 1u); - }); + testReplaceSelectRange( + {{0, 1}}, [](CollectRangesAndMasks collect) { ASSERT_EQ(collect.masks.size(), 1u); }); } TEST_F(P4CMidend, replaceSelectRange1) { - testReplaceSelectRange({{16, 255}}, [](CollectRangesAndMasks collect) { - ASSERT_EQ(collect.masks.size(), 4u); - }); + testReplaceSelectRange( + {{16, 255}}, [](CollectRangesAndMasks collect) { ASSERT_EQ(collect.masks.size(), 4u); }); } TEST_F(P4CMidend, replaceSelectRange2) { - testReplaceSelectRange({{20, 319}}, [](CollectRangesAndMasks collect) { - ASSERT_EQ(collect.masks.size(), 6u); - }); + testReplaceSelectRange( + {{20, 319}}, [](CollectRangesAndMasks collect) { ASSERT_EQ(collect.masks.size(), 6u); }); } TEST_F(P4CMidend, replaceSelectRangeSigned1) { - testReplaceSelectRange({{-4, 3}}, [](CollectRangesAndMasks collect) { - ASSERT_EQ(collect.masks.size(), 2u); - }); + testReplaceSelectRange( + {{-4, 3}}, [](CollectRangesAndMasks collect) { ASSERT_EQ(collect.masks.size(), 2u); }); } TEST_F(P4CMidend, replaceSelectRangeSigned2) { - testReplaceSelectRange({{-256, 3}}, [](CollectRangesAndMasks collect) { - ASSERT_EQ(collect.masks.size(), 2u); - }); + testReplaceSelectRange( + {{-256, 3}}, [](CollectRangesAndMasks collect) { ASSERT_EQ(collect.masks.size(), 2u); }); } TEST_F(P4CMidend, replaceSelectRangeSigned3) { - testReplaceSelectRange({{-256, 0}}, [](CollectRangesAndMasks collect) { - ASSERT_EQ(collect.masks.size(), 2u); - }); + testReplaceSelectRange( + {{-256, 0}}, [](CollectRangesAndMasks collect) { ASSERT_EQ(collect.masks.size(), 2u); }); } TEST_F(P4CMidend, replaceSelectRangeSigned4) { - testReplaceSelectRange({{-256, -1}}, [](CollectRangesAndMasks collect) { - ASSERT_EQ(collect.masks.size(), 1u); - }); + testReplaceSelectRange( + {{-256, -1}}, [](CollectRangesAndMasks collect) { ASSERT_EQ(collect.masks.size(), 1u); }); } TEST_F(P4CMidend, replaceSelectRangeSigned5) { - testReplaceSelectRange({{0, 15}}, [](CollectRangesAndMasks collect) { - ASSERT_EQ(collect.masks.size(), 1u); - }); + testReplaceSelectRange( + {{0, 15}}, [](CollectRangesAndMasks collect) { ASSERT_EQ(collect.masks.size(), 1u); }); } } // namespace Test diff --git a/test/gtest/opeq_test.cpp b/test/gtest/opeq_test.cpp index 5d35e35564..796a9f8bf9 100644 --- a/test/gtest/opeq_test.cpp +++ b/test/gtest/opeq_test.cpp @@ -1,5 +1,5 @@ /* -Copyright 2013-present Barefoot Networks, Inc. +Copyright 2013-present Barefoot Networks, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/test/gtest/ordered_map.cpp b/test/gtest/ordered_map.cpp index 85d1094f91..5ce9cf1de4 100644 --- a/test/gtest/ordered_map.cpp +++ b/test/gtest/ordered_map.cpp @@ -1,5 +1,5 @@ /* -Copyright 2013-present Barefoot Networks, Inc. +Copyright 2013-present Barefoot Networks, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,9 +14,10 @@ See the License for the specific language governing permissions and limitations under the License. */ -#include "gtest/gtest.h" #include "lib/ordered_map.h" +#include "gtest/gtest.h" + namespace Test { TEST(ordered_map, map_equal) { @@ -122,7 +123,7 @@ TEST(ordered_map, insert_emplace_erase) { typename ordered_map::const_iterator it = om.end(); for (auto v : {0, 1, 2, 3, 4, 5, 6, 7, 8}) { sm.emplace(v, 2 * v); - std::pair pair {v, 2 * v}; + std::pair pair{v, 2 * v}; if (v % 2 == 0) { if ((v / 2) % 2 == 0) { it = om.insert(pair).first; @@ -148,5 +149,4 @@ TEST(ordered_map, insert_emplace_erase) { EXPECT_TRUE(std::equal(om.begin(), om.end(), sm.begin(), sm.end())); } - } // namespace Test diff --git a/test/gtest/ordered_set.cpp b/test/gtest/ordered_set.cpp index 8206c217db..dae2bdca46 100644 --- a/test/gtest/ordered_set.cpp +++ b/test/gtest/ordered_set.cpp @@ -1,5 +1,5 @@ /* -Copyright 2013-present Barefoot Networks, Inc. +Copyright 2013-present Barefoot Networks, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,9 +14,11 @@ See the License for the specific language governing permissions and limitations under the License. */ +#include "lib/ordered_set.h" + #include + #include "gtest/gtest.h" -#include "lib/ordered_set.h" namespace Test { @@ -107,9 +109,9 @@ TEST(ordered_set, insert_erase_iterators) { } TEST(ordered_set, set_intersect) { - ordered_set a = { 5, 8, 1, 10, 4 }; - ordered_set b = { 4, 2, 9, 5, 1 }; - ordered_set expect = { 1, 4, 5 }; + ordered_set a = {5, 8, 1, 10, 4}; + ordered_set b = {4, 2, 9, 5, 1}; + ordered_set expect = {1, 4, 5}; ordered_set res; std::set_intersection(a.sorted_begin(), a.sorted_end(), b.sorted_begin(), b.sorted_end(), std::inserter(res, res.end())); diff --git a/test/gtest/p4runtime.cpp b/test/gtest/p4runtime.cpp index e0b5caac83..c0c86e4da4 100644 --- a/test/gtest/p4runtime.cpp +++ b/test/gtest/p4runtime.cpp @@ -19,11 +19,11 @@ limitations under the License. #include #include +#include #include #include #include -#include #include "control-plane/p4/config/v1/p4info.pb.h" #include "control-plane/p4/config/v1/p4types.pb.h" @@ -58,14 +58,12 @@ const cstring defaultArch = "v1model"; class ParseAnnotations : public P4::ParseAnnotations { public: - ParseAnnotations() : P4::ParseAnnotations("FrontendTest", true, { - PARSE("my_anno", StringLiteral) - }) { } + ParseAnnotations() + : P4::ParseAnnotations("FrontendTest", true, {PARSE("my_anno", StringLiteral)}) {} }; -std::optional -createP4RuntimeTestCase( - const std::string& source, +std::optional createP4RuntimeTestCase( + const std::string &source, CompilerOptions::FrontendVersion langVersion = FrontendTestCase::defaultVersion, const cstring arch = defaultArch, P4::ParseAnnotations parseAnnotations = P4::ParseAnnotations()) { @@ -74,95 +72,87 @@ createP4RuntimeTestCase( return P4::generateP4Runtime(frontendTestCase->program, arch); } -std::optional -createP4RuntimeTestCase( - const std::string& source, - P4::ParseAnnotations parseAnnotations) { - return createP4RuntimeTestCase(source, FrontendTestCase::defaultVersion, - defaultArch, parseAnnotations); +std::optional createP4RuntimeTestCase(const std::string &source, + P4::ParseAnnotations parseAnnotations) { + return createP4RuntimeTestCase(source, FrontendTestCase::defaultVersion, defaultArch, + parseAnnotations); } /// Generic meta function which searches an object by @name in the given range /// and @returns the P4Runtime representation, or null if none is found. template -auto findP4InfoObject(const It& first, const It& last, const std::string& name) - -> const typename std::iterator_traits::value_type* { +auto findP4InfoObject(const It &first, const It &last, const std::string &name) -> const + typename std::iterator_traits::value_type * { using T = typename std::iterator_traits::value_type; - auto desiredObject = std::find_if(first, last, - [&](const T& object) { - return object.preamble().name() == name; - }); + auto desiredObject = std::find_if( + first, last, [&](const T &object) { return object.preamble().name() == name; }); if (desiredObject == last) return nullptr; return &*desiredObject; } /// @return the P4Runtime representation of the table with the given name, or /// null if none is found. -const p4configv1::Table* findTable(const P4::P4RuntimeAPI& analysis, - const std::string& name) { - auto& tables = analysis.p4Info->tables(); +const p4configv1::Table *findTable(const P4::P4RuntimeAPI &analysis, const std::string &name) { + auto &tables = analysis.p4Info->tables(); return findP4InfoObject(tables.begin(), tables.end(), name); } /// @return the P4Runtime representation of the action with the given name, or /// null if none is found. -const p4configv1::Action* findAction(const P4::P4RuntimeAPI& analysis, - const std::string& name) { - auto& actions = analysis.p4Info->actions(); +const p4configv1::Action *findAction(const P4::P4RuntimeAPI &analysis, const std::string &name) { + auto &actions = analysis.p4Info->actions(); return findP4InfoObject(actions.begin(), actions.end(), name); } /// @return the P4Runtime representation of the value set with the given name, /// or null if none is found. -const p4configv1::ValueSet* findValueSet(const P4::P4RuntimeAPI& analysis, - const std::string& name) { - auto& vsets = analysis.p4Info->value_sets(); +const p4configv1::ValueSet *findValueSet(const P4::P4RuntimeAPI &analysis, + const std::string &name) { + auto &vsets = analysis.p4Info->value_sets(); return findP4InfoObject(vsets.begin(), vsets.end(), name); } /// @return the P4Runtime representation of the register with the given name, or /// null if none is found. -const p4configv1::Register* findRegister(const P4::P4RuntimeAPI& analysis, - const std::string& name) { - auto& registers = analysis.p4Info->registers(); +const p4configv1::Register *findRegister(const P4::P4RuntimeAPI &analysis, + const std::string &name) { + auto ®isters = analysis.p4Info->registers(); return findP4InfoObject(registers.begin(), registers.end(), name); } /// @return the P4Runtime representation of the counter with the given name, or /// null if none is found. -const p4configv1::Counter* findCounter(const P4::P4RuntimeAPI& analysis, - const std::string& name) { - auto& counters = analysis.p4Info->counters(); +const p4configv1::Counter *findCounter(const P4::P4RuntimeAPI &analysis, const std::string &name) { + auto &counters = analysis.p4Info->counters(); return findP4InfoObject(counters.begin(), counters.end(), name); } /// @return the P4Runtime representation of the direct counter with the given /// name, or null if none is found. -const p4configv1::DirectCounter* findDirectCounter(const P4::P4RuntimeAPI& analysis, - const std::string& name) { - auto& counters = analysis.p4Info->direct_counters(); +const p4configv1::DirectCounter *findDirectCounter(const P4::P4RuntimeAPI &analysis, + const std::string &name) { + auto &counters = analysis.p4Info->direct_counters(); return findP4InfoObject(counters.begin(), counters.end(), name); } /// @return the P4Runtime representation of the digest with the given name, or /// null if none is found. -const p4configv1::Digest* findDigest(const P4::P4RuntimeAPI& analysis, - const std::string& name) { - auto& digests = analysis.p4Info->digests(); +const p4configv1::Digest *findDigest(const P4::P4RuntimeAPI &analysis, const std::string &name) { + auto &digests = analysis.p4Info->digests(); return findP4InfoObject(digests.begin(), digests.end(), name); } /// @return the P4Runtime representation of the "controller header" with the /// given name, or null if none is found. -const p4configv1::ControllerPacketMetadata* findControllerHeader(const P4::P4RuntimeAPI& analysis, - const std::string& name) { - auto& headers = analysis.p4Info->controller_packet_metadata(); +const p4configv1::ControllerPacketMetadata *findControllerHeader(const P4::P4RuntimeAPI &analysis, + const std::string &name) { + auto &headers = analysis.p4Info->controller_packet_metadata(); return findP4InfoObject(headers.begin(), headers.end(), name); } } // namespace -class P4Runtime : public P4CTest { }; +class P4Runtime : public P4CTest {}; TEST_F(P4Runtime, IdAssignment) { auto test = createP4RuntimeTestCase(P4_SOURCE(P4Headers::V1MODEL, R"( @@ -261,7 +251,7 @@ TEST_F(P4Runtime, IdAssignment) { { // Check that 'igTable' ended up in the P4Info output. - auto* igTable = findTable(*test, "ingress.igTable"); + auto *igTable = findTable(*test, "ingress.igTable"); ASSERT_TRUE(igTable != nullptr); // Check that the id indicates the correct resource type. @@ -278,7 +268,7 @@ TEST_F(P4Runtime, IdAssignment) { // name, which is determined by its @name annotation, and *not* under // 'igTableWithoutName'. EXPECT_TRUE(findTable(*test, "ingress.igTableWithoutName") == nullptr); - auto* igTableWithName = findTable(*test, "ingress.igTableWithName"); + auto *igTableWithName = findTable(*test, "ingress.igTableWithName"); ASSERT_TRUE(igTableWithName != nullptr); // Check that the id of 'igTableWithName' was computed based on its @@ -291,7 +281,7 @@ TEST_F(P4Runtime, IdAssignment) { // Check that 'igTableWithId' ended up in the P4Info output, and that // its id matches the one set by its @id annotation, with the required // 8-bit type prefix (which is 0x2 for tables). - auto* igTableWithId = findTable(*test, "ingress.igTableWithId"); + auto *igTableWithId = findTable(*test, "ingress.igTableWithId"); ASSERT_TRUE(igTableWithId != nullptr); auto expectedId = 1234u | (unsigned(P4Ids::TABLE) << 24); EXPECT_EQ(expectedId, igTableWithId->preamble().id()); @@ -299,7 +289,7 @@ TEST_F(P4Runtime, IdAssignment) { { // Same as above, but with the largest possible id (0xffffff). - auto* igTableWithLargestId = findTable(*test, "ingress.igTableWithLargestId"); + auto *igTableWithLargestId = findTable(*test, "ingress.igTableWithLargestId"); ASSERT_TRUE(igTableWithLargestId != nullptr); auto expectedId = 0xffffffu | (unsigned(P4Ids::TABLE) << 24); EXPECT_EQ(expectedId, igTableWithLargestId->preamble().id()); @@ -308,7 +298,7 @@ TEST_F(P4Runtime, IdAssignment) { { // Check that 'igTableWithPrefixedId' ended up in the P4Info output, and // that its id matches the one set by its @id annotation. - auto* igTableWithPrefixedId = findTable(*test, "ingress.igTableWithPrefixedId"); + auto *igTableWithPrefixedId = findTable(*test, "ingress.igTableWithPrefixedId"); ASSERT_TRUE(igTableWithPrefixedId != nullptr); auto expectedId = 0x02000133u; EXPECT_EQ(expectedId, igTableWithPrefixedId->preamble().id()); @@ -319,7 +309,7 @@ TEST_F(P4Runtime, IdAssignment) { // that name, and that its id matches the one set by its @id annotation // - in other words, that @id takes precedence over @name. EXPECT_TRUE(findTable(*test, "ingress.igTableWithoutNameAndId") == nullptr); - auto* igTableWithNameAndId = findTable(*test, "ingress.igTableWithNameAndId"); + auto *igTableWithNameAndId = findTable(*test, "ingress.igTableWithNameAndId"); ASSERT_TRUE(igTableWithNameAndId != nullptr); auto expectedId = 5678u | (unsigned(P4Ids::TABLE) << 24); EXPECT_EQ(expectedId, igTableWithNameAndId->preamble().id()); @@ -328,14 +318,13 @@ TEST_F(P4Runtime, IdAssignment) { { // Check that the two tables with conflicting ids are both present, and // that they didn't end up with the same id in the P4Info output. - auto* conflictingTableA = findTable(*test, "ingress.conflictingTableA"); + auto *conflictingTableA = findTable(*test, "ingress.conflictingTableA"); ASSERT_TRUE(conflictingTableA != nullptr); - auto* conflictingTableB = findTable(*test, "ingress.conflictingTableB"); + auto *conflictingTableB = findTable(*test, "ingress.conflictingTableB"); ASSERT_TRUE(conflictingTableB != nullptr); EXPECT_TRUE(conflictingTableA->preamble().id() == 0x02000134 || conflictingTableB->preamble().id() == 0x02000134); - EXPECT_NE(conflictingTableA->preamble().id(), - conflictingTableB->preamble().id()); + EXPECT_NE(conflictingTableA->preamble().id(), conflictingTableB->preamble().id()); } } @@ -429,30 +418,30 @@ TEST_F(P4Runtime, FieldIdAssignment) { { // Check the ids for igTable's match fields. - auto* igTable = findTable(*test, "ingress.igTable"); + auto *igTable = findTable(*test, "ingress.igTable"); ASSERT_TRUE(igTable != nullptr); - const auto& mf1 = igTable->match_fields(0); - const auto& mf2 = igTable->match_fields(1); + const auto &mf1 = igTable->match_fields(0); + const auto &mf2 = igTable->match_fields(1); EXPECT_EQ(99u, mf1.id()); EXPECT_NE(99u, mf2.id()); } { // Check the ids for action a's parameters. - auto* aAction = findAction(*test, "ingress.a"); + auto *aAction = findAction(*test, "ingress.a"); ASSERT_TRUE(aAction != nullptr); - const auto& ap1 = aAction->params(0); - const auto& ap2 = aAction->params(1); + const auto &ap1 = aAction->params(0); + const auto &ap2 = aAction->params(1); EXPECT_EQ(99u, ap1.id()); EXPECT_NE(99u, ap2.id()); } { // Check the ids for the packet-in header fields. - auto* packetInHeader = findControllerHeader(*test, "packet_in"); + auto *packetInHeader = findControllerHeader(*test, "packet_in"); ASSERT_TRUE(packetInHeader != nullptr); - const auto& m1 = packetInHeader->metadata(0); - const auto& m2 = packetInHeader->metadata(1); + const auto &m1 = packetInHeader->metadata(0); + const auto &m2 = packetInHeader->metadata(1); EXPECT_NE(1u, m1.id()); EXPECT_EQ(1u, m2.id()); } @@ -460,10 +449,10 @@ TEST_F(P4Runtime, FieldIdAssignment) { { // Check the ids for igTableNoAnno's match fields. Without @id // annotations, the ids should be assigned sequentially, starting at 1. - auto* igTable = findTable(*test, "ingress.igTableNoAnno"); + auto *igTable = findTable(*test, "ingress.igTableNoAnno"); ASSERT_TRUE(igTable != nullptr); - const auto& mf1 = igTable->match_fields(0); - const auto& mf2 = igTable->match_fields(1); + const auto &mf1 = igTable->match_fields(0); + const auto &mf2 = igTable->match_fields(1); EXPECT_EQ(1u, mf1.id()); EXPECT_EQ(2u, mf2.id()); } @@ -472,17 +461,17 @@ TEST_F(P4Runtime, FieldIdAssignment) { // Check the ids for igTableLargeId's match fields. The compiler should // be able to handle all unsigned 32-bit integers greater than 0, // including 0xffffffff. - auto* igTable = findTable(*test, "ingress.igTableLargeId"); + auto *igTable = findTable(*test, "ingress.igTableLargeId"); ASSERT_TRUE(igTable != nullptr); - const auto& mf1 = igTable->match_fields(0); + const auto &mf1 = igTable->match_fields(0); EXPECT_EQ(0xffffffff, mf1.id()); } { auto vset = findValueSet(*test, "parse.pvs"); ASSERT_TRUE(vset != nullptr); - const auto& mf1 = vset->match(0); - const auto& mf2 = vset->match(1); + const auto &mf1 = vset->match(0); + const auto &mf2 = vset->match(1); EXPECT_EQ(33u, mf1.id()); EXPECT_NE(33u, mf2.id()); } @@ -539,28 +528,27 @@ TEST_F(P4Runtime, IdAssignmentCounters) { ASSERT_TRUE(test); EXPECT_EQ(0u, ::diagnosticCount()); - // checks that myDirectCounter1 with the right ID prefix { - auto* myTable1 = findTable(*test, "myTable1"); + auto *myTable1 = findTable(*test, "myTable1"); ASSERT_TRUE(myTable1 != nullptr); - auto* myDirectCounter1 = findDirectCounter(*test, "myDirectCounter1"); + auto *myDirectCounter1 = findDirectCounter(*test, "myDirectCounter1"); ASSERT_TRUE(myDirectCounter1 != nullptr); EXPECT_EQ(unsigned(P4Ids::DIRECT_COUNTER), myDirectCounter1->preamble().id() >> 24); EXPECT_EQ(myDirectCounter1->preamble().id(), myTable1->direct_resource_ids(0)); } // checks that myDirectCounter2 with the right ID prefix { - auto* myTable2 = findTable(*test, "myTable2"); + auto *myTable2 = findTable(*test, "myTable2"); ASSERT_TRUE(myTable2 != nullptr); - auto* myDirectCounter2 = findDirectCounter(*test, "myDirectCounter2"); + auto *myDirectCounter2 = findDirectCounter(*test, "myDirectCounter2"); ASSERT_TRUE(myDirectCounter2 != nullptr); EXPECT_EQ(unsigned(P4Ids::DIRECT_COUNTER), myDirectCounter2->preamble().id() >> 24); EXPECT_EQ(myDirectCounter2->preamble().id(), myTable2->direct_resource_ids(0)); } // checks that myCounter with the right ID prefix { - auto* myCounter = findCounter(*test, "myCounter"); + auto *myCounter = findCounter(*test, "myCounter"); ASSERT_TRUE(myCounter != nullptr); EXPECT_EQ(unsigned(P4Ids::COUNTER), myCounter->preamble().id() >> 24); } @@ -688,50 +676,50 @@ TEST_F(P4Runtime, P4_16_MatchFields) { ASSERT_TRUE(test); EXPECT_EQ(0u, ::diagnosticCount()); - auto* igTable = findTable(*test, "ingress.igTable"); + auto *igTable = findTable(*test, "ingress.igTable"); ASSERT_TRUE(igTable != nullptr); EXPECT_EQ(39, igTable->match_fields_size()); std::vector expected = { - { 1, "h.h.headerField", 16, MatchField::EXACT, "" }, - { 2, "m.metadataField", 33, MatchField::EXACT, "" }, - { 3, "h.hStack[3].headerField", 16, MatchField::EXACT, "" }, - { 4, "h.h.headerField", 16, MatchField::TERNARY, "" }, - { 5, "m.metadataField", 33, MatchField::TERNARY, "" }, - { 6, "h.hStack[3].headerField", 16, MatchField::TERNARY, "" }, - { 7, "h.h.headerField", 16, MatchField::LPM, "" }, - { 8, "m.metadataField", 33, MatchField::LPM, "" }, - { 9, "h.hStack[3].headerField", 16, MatchField::LPM, "" }, - { 10, "h.h.headerField", 16, MatchField::RANGE, "" }, - { 11, "m.metadataField", 33, MatchField::RANGE, "" }, - { 12, "h.hStack[3].headerField", 16, MatchField::RANGE, "" }, - { 13, "h.h.$valid$", 1, MatchField::EXACT, "" }, - { 14, "h.h.$valid$", 1, MatchField::TERNARY, "" }, - { 15, "h.hStack[3].$valid$", 1, MatchField::EXACT, "" }, - { 16, "h.hStack[3].$valid$", 1, MatchField::TERNARY, "" }, - { 17, "h.h.headerField & 13", 16, MatchField::EXACT, "" }, - { 18, "h.h.headerField & 13", 16, MatchField::TERNARY, "" }, - { 19, "h.h.headerField[13:4]", 10, MatchField::EXACT, "" }, - { 20, "h.h.headerField[13:4]", 10, MatchField::TERNARY, "" }, - { 21, "h.hUnion.a.headerField", 16, MatchField::EXACT, "" }, - { 22, "h.hUnion.a.headerField", 16, MatchField::TERNARY, "" }, - { 23, "h.hUnion.a.headerField", 16, MatchField::LPM, "" }, - { 24, "h.hUnion.a.headerField", 16, MatchField::RANGE, "" }, - { 25, "h.hUnion.b.anotherHeaderField", 8, MatchField::EXACT, "" }, - { 26, "h.hUnion.b.anotherHeaderField", 8, MatchField::TERNARY, "" }, - { 27, "h.hUnion.b.anotherHeaderField", 8, MatchField::LPM, "" }, - { 28, "h.hUnion.b.anotherHeaderField", 8, MatchField::RANGE, "" }, - { 29, "h.hUnion.a.$valid$", 1, MatchField::EXACT, "" }, - { 30, "h.hUnion.a.$valid$", 1, MatchField::TERNARY, "" }, - { 31, "h.hUnion.b.$valid$", 1, MatchField::EXACT, "" }, - { 32, "h.hUnion.b.$valid$", 1, MatchField::TERNARY, "" }, - { 33, "h.hUnion.$valid$", 1, MatchField::EXACT, "" }, - { 34, "h.hUnion.$valid$", 1, MatchField::TERNARY, "" }, - { 35, "lShift", 16, MatchField::EXACT, "" }, - { 36, "lShift", 16, MatchField::TERNARY, "" }, - { 37, "plusSix", 16, MatchField::EXACT, "" }, - { 38, "plusSix", 16, MatchField::TERNARY, "" }, - { 39, "h.hUnion.c.yetAnotherHeaderField", 8, MatchField::EXACT, "CustomT_t" }, + {1, "h.h.headerField", 16, MatchField::EXACT, ""}, + {2, "m.metadataField", 33, MatchField::EXACT, ""}, + {3, "h.hStack[3].headerField", 16, MatchField::EXACT, ""}, + {4, "h.h.headerField", 16, MatchField::TERNARY, ""}, + {5, "m.metadataField", 33, MatchField::TERNARY, ""}, + {6, "h.hStack[3].headerField", 16, MatchField::TERNARY, ""}, + {7, "h.h.headerField", 16, MatchField::LPM, ""}, + {8, "m.metadataField", 33, MatchField::LPM, ""}, + {9, "h.hStack[3].headerField", 16, MatchField::LPM, ""}, + {10, "h.h.headerField", 16, MatchField::RANGE, ""}, + {11, "m.metadataField", 33, MatchField::RANGE, ""}, + {12, "h.hStack[3].headerField", 16, MatchField::RANGE, ""}, + {13, "h.h.$valid$", 1, MatchField::EXACT, ""}, + {14, "h.h.$valid$", 1, MatchField::TERNARY, ""}, + {15, "h.hStack[3].$valid$", 1, MatchField::EXACT, ""}, + {16, "h.hStack[3].$valid$", 1, MatchField::TERNARY, ""}, + {17, "h.h.headerField & 13", 16, MatchField::EXACT, ""}, + {18, "h.h.headerField & 13", 16, MatchField::TERNARY, ""}, + {19, "h.h.headerField[13:4]", 10, MatchField::EXACT, ""}, + {20, "h.h.headerField[13:4]", 10, MatchField::TERNARY, ""}, + {21, "h.hUnion.a.headerField", 16, MatchField::EXACT, ""}, + {22, "h.hUnion.a.headerField", 16, MatchField::TERNARY, ""}, + {23, "h.hUnion.a.headerField", 16, MatchField::LPM, ""}, + {24, "h.hUnion.a.headerField", 16, MatchField::RANGE, ""}, + {25, "h.hUnion.b.anotherHeaderField", 8, MatchField::EXACT, ""}, + {26, "h.hUnion.b.anotherHeaderField", 8, MatchField::TERNARY, ""}, + {27, "h.hUnion.b.anotherHeaderField", 8, MatchField::LPM, ""}, + {28, "h.hUnion.b.anotherHeaderField", 8, MatchField::RANGE, ""}, + {29, "h.hUnion.a.$valid$", 1, MatchField::EXACT, ""}, + {30, "h.hUnion.a.$valid$", 1, MatchField::TERNARY, ""}, + {31, "h.hUnion.b.$valid$", 1, MatchField::EXACT, ""}, + {32, "h.hUnion.b.$valid$", 1, MatchField::TERNARY, ""}, + {33, "h.hUnion.$valid$", 1, MatchField::EXACT, ""}, + {34, "h.hUnion.$valid$", 1, MatchField::TERNARY, ""}, + {35, "lShift", 16, MatchField::EXACT, ""}, + {36, "lShift", 16, MatchField::TERNARY, ""}, + {37, "plusSix", 16, MatchField::EXACT, ""}, + {38, "plusSix", 16, MatchField::TERNARY, ""}, + {39, "h.hUnion.c.yetAnotherHeaderField", 8, MatchField::EXACT, "CustomT_t"}, }; for (auto i = 0; i < igTable->match_fields_size(); i++) { @@ -795,34 +783,35 @@ TEST_F(P4Runtime, DISABLED_P4_14_MatchFields) { } control ingress { apply(igTable); } - )"), CompilerOptions::FrontendVersion::P4_14); + )"), + CompilerOptions::FrontendVersion::P4_14); ASSERT_TRUE(test); EXPECT_EQ(0u, ::diagnosticCount()); - auto* igTable = findTable(*test, "igTable"); + auto *igTable = findTable(*test, "igTable"); ASSERT_TRUE(igTable != nullptr); EXPECT_EQ(18, igTable->match_fields_size()); std::vector expected = { - { 1, "h.headerField", 16, MatchField::EXACT }, - { 2, "m.metadataField", 33, MatchField::EXACT }, - { 3, "hStack[3].headerField", 16, MatchField::EXACT }, - { 4, "h.headerField", 16, MatchField::TERNARY }, - { 5, "m.metadataField", 33, MatchField::TERNARY }, - { 6, "hStack[3].headerField", 16, MatchField::TERNARY }, - { 7, "h.headerField", 16, MatchField::LPM }, - { 8, "m.metadataField", 33, MatchField::LPM }, - { 9, "hStack[3].headerField", 16, MatchField::LPM }, - { 10, "h.headerField", 16, MatchField::RANGE }, - { 11, "m.metadataField", 33, MatchField::RANGE }, - { 12, "hStack[3].headerField", 16, MatchField::RANGE }, - { 13, "h.$valid$", 1, MatchField::EXACT }, - { 14, "hStack[3].$valid$", 1, MatchField::EXACT }, - { 15, "h.headerField", 2, MatchField::EXACT }, - { 16, "h.headerField", 2, MatchField::TERNARY }, - { 17, "h.headerField", 16, MatchField::EXACT }, - { 18, "h.headerField", 16, MatchField::TERNARY }, + {1, "h.headerField", 16, MatchField::EXACT}, + {2, "m.metadataField", 33, MatchField::EXACT}, + {3, "hStack[3].headerField", 16, MatchField::EXACT}, + {4, "h.headerField", 16, MatchField::TERNARY}, + {5, "m.metadataField", 33, MatchField::TERNARY}, + {6, "hStack[3].headerField", 16, MatchField::TERNARY}, + {7, "h.headerField", 16, MatchField::LPM}, + {8, "m.metadataField", 33, MatchField::LPM}, + {9, "hStack[3].headerField", 16, MatchField::LPM}, + {10, "h.headerField", 16, MatchField::RANGE}, + {11, "m.metadataField", 33, MatchField::RANGE}, + {12, "hStack[3].headerField", 16, MatchField::RANGE}, + {13, "h.$valid$", 1, MatchField::EXACT}, + {14, "hStack[3].$valid$", 1, MatchField::EXACT}, + {15, "h.headerField", 2, MatchField::EXACT}, + {16, "h.headerField", 2, MatchField::TERNARY}, + {17, "h.headerField", 16, MatchField::EXACT}, + {18, "h.headerField", 16, MatchField::TERNARY}, }; for (auto i = 0; i < igTable->match_fields_size(); i++) { @@ -988,7 +977,8 @@ TEST_F(P4Runtime, PSADigests) { EgressPipeline(MyEP(), MyEC(), MyED()) ep; PSA_Switch(ip, PacketReplicationEngine(), ep, BufferingQueueingEngine()) main; - )"), CompilerOptions::FrontendVersion::P4_16, "psa"); + )"), + CompilerOptions::FrontendVersion::P4_16, "psa"); ASSERT_TRUE(test); // 0 warnings @@ -1083,7 +1073,7 @@ TEST_F(P4Runtime, StaticTableEntries) { EXPECT_EQ(1u, ::diagnosticCount()); auto entries = test->entries; - const auto& updates = entries->updates(); + const auto &updates = entries->updates(); ASSERT_EQ(6, updates.size()); { @@ -1097,30 +1087,29 @@ TEST_F(P4Runtime, StaticTableEntries) { ASSERT_TRUE(action != nullptr); int priority = 1000; - auto check_entry = [&](const p4v1::Update& update, - const std::string& exact_v, - const std::optional& ternary_v, - const std::optional& ternary_mask, - const std::string& param_v) { + auto check_entry = [&](const p4v1::Update &update, const std::string &exact_v, + const std::optional &ternary_v, + const std::optional &ternary_mask, + const std::string ¶m_v) { EXPECT_EQ(p4v1::Update::INSERT, update.type()); - const auto& protoEntry = update.entity().table_entry(); + const auto &protoEntry = update.entity().table_entry(); EXPECT_EQ(table->preamble().id(), protoEntry.table_id()); ASSERT_EQ((ternary_v == std::nullopt) ? 1 : 2, protoEntry.match().size()); - const auto& mfA = protoEntry.match().Get(0); + const auto &mfA = protoEntry.match().Get(0); EXPECT_EQ(hfAId, mfA.field_id()); EXPECT_EQ(exact_v, mfA.exact().value()); if (ternary_v != std::nullopt) { - const auto& mfB = protoEntry.match().Get(1); - EXPECT_EQ(hfBId, mfB.field_id()); - EXPECT_EQ(*ternary_v, mfB.ternary().value()); - EXPECT_EQ(*ternary_mask, mfB.ternary().mask()); + const auto &mfB = protoEntry.match().Get(1); + EXPECT_EQ(hfBId, mfB.field_id()); + EXPECT_EQ(*ternary_v, mfB.ternary().value()); + EXPECT_EQ(*ternary_mask, mfB.ternary().mask()); } - const auto& protoAction = protoEntry.action().action(); + const auto &protoAction = protoEntry.action().action(); EXPECT_EQ(action->preamble().id(), protoAction.action_id()); ASSERT_EQ(1, protoAction.params().size()); - const auto& param = protoAction.params().Get(0); + const auto ¶m = protoAction.params().Get(0); EXPECT_EQ(xId, param.param_id()); EXPECT_EQ(param_v, param.value()); @@ -1147,21 +1136,20 @@ TEST_F(P4Runtime, StaticTableEntries) { auto action = findAction(*test, "ingress.a_with_bool_param"); ASSERT_TRUE(action != nullptr); - auto check_entry = [&](const p4v1::Update& update, - const std::string& exact_v, - const std::string& param_v) { + auto check_entry = [&](const p4v1::Update &update, const std::string &exact_v, + const std::string ¶m_v) { EXPECT_EQ(p4v1::Update::INSERT, update.type()); - const auto& protoEntry = update.entity().table_entry(); + const auto &protoEntry = update.entity().table_entry(); EXPECT_EQ(table->preamble().id(), protoEntry.table_id()); ASSERT_EQ(1, protoEntry.match().size()); - const auto& mf = protoEntry.match().Get(0); + const auto &mf = protoEntry.match().Get(0); EXPECT_EQ(exact_v, mf.exact().value()); - const auto& protoAction = protoEntry.action().action(); + const auto &protoAction = protoEntry.action().action(); EXPECT_EQ(action->preamble().id(), protoAction.action_id()); ASSERT_EQ(1, protoAction.params().size()); - const auto& param = protoAction.params().Get(0); + const auto ¶m = protoAction.params().Get(0); EXPECT_EQ(param_v, param.value()); }; // We assume that the entries are generated in the same order as they @@ -1262,13 +1250,13 @@ TEST_F(P4Runtime, TableActionsAnnotations) { // finds action reference based on the action name // returns nullptr if something goes wrong (e.g. not a valid action name for // this table) - auto findActionRef = [test, table](const std::string& name) -> const p4configv1::ActionRef*{ + auto findActionRef = [test, table](const std::string &name) -> const p4configv1::ActionRef * { auto action = findAction(*test, name); if (!action) return nullptr; - auto find_it = std::find_if( - table->action_refs().begin(), table->action_refs().end(), - [action](const p4configv1::ActionRef& ref) { - return ref.id() == action->preamble().id(); }); + auto find_it = std::find_if(table->action_refs().begin(), table->action_refs().end(), + [action](const p4configv1::ActionRef &ref) { + return ref.id() == action->preamble().id(); + }); return (find_it != table->action_refs().end()) ? &*find_it : nullptr; }; auto actionRefA = findActionRef("ingress.a"); @@ -1313,7 +1301,8 @@ TEST_F(P4Runtime, ValueSet) { inout standard_metadata_t sm) { apply { } } V1Switch(parse(), verifyChecksum(), ingress(), egress(), computeChecksum(), deparse()) main; - )"), ParseAnnotations()); + )"), + ParseAnnotations()); ASSERT_TRUE(test); EXPECT_EQ(0u, ::diagnosticCount()); @@ -1325,23 +1314,25 @@ TEST_F(P4Runtime, ValueSet) { ASSERT_EQ(vset->match_size(), 3); using MatchField = p4configv1::MatchField; - auto checkMatchField = [](const p4configv1::MatchField& mf, - unsigned int id, cstring name, - const std::vector annotations, - int bitwidth, + auto checkMatchField = [](const p4configv1::MatchField &mf, unsigned int id, cstring name, + const std::vector annotations, int bitwidth, std::optional matchType, std::optional otherMatchType) { EXPECT_EQ(mf.id(), id); EXPECT_EQ(mf.name(), name); ASSERT_EQ(static_cast(mf.annotations_size()), annotations.size()); for (int i = 0; i < mf.annotations_size(); i++) - EXPECT_EQ(mf.annotations(i), annotations.at(i)); + EXPECT_EQ(mf.annotations(i), annotations.at(i)); EXPECT_EQ(mf.bitwidth(), bitwidth); - if (matchType) { EXPECT_EQ(mf.match_type(), *matchType); } - if (otherMatchType) { EXPECT_EQ(mf.other_match_type(), *otherMatchType); } + if (matchType) { + EXPECT_EQ(mf.match_type(), *matchType); + } + if (otherMatchType) { + EXPECT_EQ(mf.other_match_type(), *otherMatchType); + } }; - checkMatchField(vset->match(0), 1, "f1", {"@my_anno(\"body\")"}, 8, - MatchField::TERNARY, std::nullopt); + checkMatchField(vset->match(0), 1, "f1", {"@my_anno(\"body\")"}, 8, MatchField::TERNARY, + std::nullopt); checkMatchField(vset->match(1), 2, "f2", {}, 8, MatchField::EXACT, std::nullopt); checkMatchField(vset->match(2), 3, "f3", {}, 8, std::nullopt, cstring("custom")); } @@ -1370,7 +1361,8 @@ TEST_F(P4Runtime, Register) { my_register_2.write(7w10, h.h); } } V1Switch(parse(), verifyChecksum(), ingress(), egress(), computeChecksum(), deparse()) main; - )"), ParseAnnotations()); + )"), + ParseAnnotations()); ASSERT_TRUE(test); EXPECT_EQ(0u, ::diagnosticCount()); @@ -1379,11 +1371,11 @@ TEST_F(P4Runtime, Register) { auto register_ = findRegister(*test, "ingress.my_register_1"); ASSERT_TRUE(register_ != nullptr); EXPECT_EQ(unsigned(P4Ids::REGISTER), register_->preamble().id() >> 24); - const auto& annotations = register_->preamble().annotations(); + const auto &annotations = register_->preamble().annotations(); ASSERT_EQ(1, annotations.size()); EXPECT_EQ("@my_anno(\"This is an annotation!\")", annotations.Get(0)); EXPECT_EQ(128, register_->size()); - const auto& typeSpec = register_->type_spec(); + const auto &typeSpec = register_->type_spec(); ASSERT_TRUE(typeSpec.has_tuple()); EXPECT_EQ(2, typeSpec.tuple().members_size()); } @@ -1392,7 +1384,7 @@ TEST_F(P4Runtime, Register) { ASSERT_TRUE(register_ != nullptr); EXPECT_EQ(unsigned(P4Ids::REGISTER), register_->preamble().id() >> 24); EXPECT_EQ(128, register_->size()); - const auto& typeSpec = register_->type_spec(); + const auto &typeSpec = register_->type_spec(); ASSERT_TRUE(typeSpec.has_header()); EXPECT_EQ("Header", typeSpec.header().name()); } @@ -1440,41 +1432,43 @@ TEST_F(P4Runtime, Documentation) { EXPECT_EQ(0u, ::diagnosticCount()); { - auto table = findTable(*test, "ingress.t"); - ASSERT_TRUE(table != nullptr); - const auto& tDocumentation = table->preamble().doc(); - EXPECT_EQ(tDocumentation.brief(), ""); - // NOLINTNEXTLINE(whitespace/line_length) - EXPECT_EQ(tDocumentation.description(), "A table that matches on the ingress port and decides whether or not to drop the packet"); - - const auto& mf = table->match_fields(0); - const auto& mfDocumentation = mf.doc(); - EXPECT_EQ(mfDocumentation.brief(), "Ingress port"); - EXPECT_EQ(mfDocumentation.description(), ""); + auto table = findTable(*test, "ingress.t"); + ASSERT_TRUE(table != nullptr); + const auto &tDocumentation = table->preamble().doc(); + EXPECT_EQ(tDocumentation.brief(), ""); + // NOLINTNEXTLINE(whitespace/line_length) + EXPECT_EQ(tDocumentation.description(), + "A table that matches on the ingress port and decides whether or not to drop the " + "packet"); + + const auto &mf = table->match_fields(0); + const auto &mfDocumentation = mf.doc(); + EXPECT_EQ(mfDocumentation.brief(), "Ingress port"); + EXPECT_EQ(mfDocumentation.description(), ""); } { - auto noop = findAction(*test, "ingress.noop"); - ASSERT_TRUE(noop != nullptr); - const auto& aDocumentation = noop->preamble().doc(); - EXPECT_EQ(aDocumentation.brief(), "This action does nothing duh!"); - EXPECT_EQ(aDocumentation.description(), ""); + auto noop = findAction(*test, "ingress.noop"); + ASSERT_TRUE(noop != nullptr); + const auto &aDocumentation = noop->preamble().doc(); + EXPECT_EQ(aDocumentation.brief(), "This action does nothing duh!"); + EXPECT_EQ(aDocumentation.description(), ""); } { - auto drop = findAction(*test, "ingress.drop"); - ASSERT_TRUE(drop != nullptr); - EXPECT_FALSE(drop->preamble().has_doc()); + auto drop = findAction(*test, "ingress.drop"); + ASSERT_TRUE(drop != nullptr); + EXPECT_FALSE(drop->preamble().has_doc()); } } class P4RuntimePkgInfo : public P4CTest { protected: - static std::optional createTestCase(const char* annotations); + static std::optional createTestCase(const char *annotations); }; /* static */ -std::optional P4RuntimePkgInfo::createTestCase(const char* annotations) { +std::optional P4RuntimePkgInfo::createTestCase(const char *annotations) { auto source = P4_SOURCE(P4Headers::V1MODEL, R"( struct Headers { } struct Metadata { } @@ -1501,7 +1495,7 @@ TEST_F(P4RuntimePkgInfo, NoAnnotations) { auto test = createTestCase(""); ASSERT_TRUE(test); EXPECT_EQ(0u, ::diagnosticCount()); - const auto& pkgInfo = test->p4Info->pkg_info(); + const auto &pkgInfo = test->p4Info->pkg_info(); EXPECT_EQ(pkgInfo.arch(), "v1model"); } @@ -1512,7 +1506,7 @@ TEST_F(P4RuntimePkgInfo, GeneralCase) { @brief("This is a P4 program"))"); ASSERT_TRUE(test); EXPECT_EQ(0u, ::diagnosticCount()); - const auto& pkgInfo = test->p4Info->pkg_info(); + const auto &pkgInfo = test->p4Info->pkg_info(); EXPECT_EQ(pkgInfo.arch(), "v1model"); EXPECT_EQ(pkgInfo.name(), "prog.p4"); EXPECT_EQ(pkgInfo.version(), "1.0.0"); @@ -1524,7 +1518,7 @@ TEST_F(P4RuntimePkgInfo, OverrideArch) { ASSERT_TRUE(test); // we expect 1 warning for overriding the architecture EXPECT_EQ(1u, ::diagnosticCount()); - const auto& pkgInfo = test->p4Info->pkg_info(); + const auto &pkgInfo = test->p4Info->pkg_info(); EXPECT_EQ(pkgInfo.arch(), "v1"); } @@ -1533,7 +1527,7 @@ TEST_F(P4RuntimePkgInfo, ValueNotAString) { ASSERT_TRUE(test); // we expect 1 error message EXPECT_EQ(1u, ::diagnosticCount()); - const auto& pkgInfo = test->p4Info->pkg_info(); + const auto &pkgInfo = test->p4Info->pkg_info(); EXPECT_EQ(pkgInfo.name(), ""); } @@ -1551,8 +1545,8 @@ TEST_F(P4RuntimePkgInfo, UnknownAnnotations) { @my_annotation_4("test"))"); ASSERT_TRUE(test); EXPECT_EQ(0u, ::diagnosticCount()); - const auto& pkgInfo = test->p4Info->pkg_info(); - const auto& annotations = pkgInfo.annotations(); + const auto &pkgInfo = test->p4Info->pkg_info(); + const auto &annotations = pkgInfo.annotations(); ASSERT_EQ(annotations.size(), 4); // P4 order is preserved when building the IR and generating P4Info EXPECT_EQ(annotations.Get(0), "@my_annotation_1"); @@ -1570,19 +1564,19 @@ TEST_F(P4RuntimePkgInfo, UnknownStructuredAnnotations) { @my_annotation_3[label="text", my_bool=true, int_val=2*3])"); ASSERT_TRUE(test); EXPECT_EQ(0u, ::diagnosticCount()); - const auto& pkgInfo = test->p4Info->pkg_info(); - const auto& annotations = pkgInfo.structured_annotations(); + const auto &pkgInfo = test->p4Info->pkg_info(); + const auto &annotations = pkgInfo.structured_annotations(); ASSERT_EQ(annotations.size(), 3); // P4 order is preserved when building the IR and generating P4Info { - const auto& annotation = annotations.Get(0); + const auto &annotation = annotations.Get(0); EXPECT_EQ(annotation.name(), "my_annotation_1"); EXPECT_EQ(annotation.body_case(), p4configv1::StructuredAnnotation::BODY_NOT_SET); } { - const auto& annotation = annotations.Get(1); + const auto &annotation = annotations.Get(1); EXPECT_EQ(annotation.name(), "my_annotation_2"); - const auto& expressions = annotation.expression_list().expressions(); + const auto &expressions = annotation.expression_list().expressions(); ASSERT_EQ(expressions.size(), 5); EXPECT_EQ(expressions.Get(0).int64_value(), 1); EXPECT_EQ(expressions.Get(1).string_value(), "hello"); @@ -1591,22 +1585,22 @@ TEST_F(P4RuntimePkgInfo, UnknownStructuredAnnotations) { EXPECT_EQ(expressions.Get(4).int64_value(), 11); } { - const auto& annotation = annotations.Get(2); + const auto &annotation = annotations.Get(2); EXPECT_EQ(annotation.name(), "my_annotation_3"); - const auto& kvpairs = annotation.kv_pair_list().kv_pairs(); + const auto &kvpairs = annotation.kv_pair_list().kv_pairs(); ASSERT_EQ(kvpairs.size(), 3); { - const auto& kvpair = kvpairs.Get(0); + const auto &kvpair = kvpairs.Get(0); EXPECT_EQ(kvpair.key(), "label"); EXPECT_EQ(kvpair.value().string_value(), "text"); } { - const auto& kvpair = kvpairs.Get(1); + const auto &kvpair = kvpairs.Get(1); EXPECT_EQ(kvpair.key(), "my_bool"); EXPECT_EQ(kvpair.value().bool_value(), true); } { - const auto& kvpair = kvpairs.Get(2); + const auto &kvpair = kvpairs.Get(2); EXPECT_EQ(kvpair.key(), "int_val"); EXPECT_EQ(kvpair.value().int64_value(), 6); } @@ -1636,29 +1630,26 @@ TEST_F(P4RuntimePkgInfo, StructuredAnnotationLargeInt) { EXPECT_EQ(1u, ::diagnosticCount()); } - class P4RuntimeDataTypeSpec : public P4Runtime { protected: - const IR::P4Program* getProgram(const std::string& programStr) { + const IR::P4Program *getProgram(const std::string &programStr) { auto pgm = P4::parseP4String(programStr, CompilerOptions::FrontendVersion::P4_16); if (pgm == nullptr) return nullptr; - PassManager passes({ - new P4::ParseAnnotations("P4RuntimeDataTypeSpecTest", false, { - {"p4runtime_translation", - &P4::ParseAnnotations::parseP4rtTranslationAnnotation}, - }), - new P4::ResolveReferences(&refMap), - new P4::TypeInference(&refMap, &typeMap, false) - }); + PassManager passes( + {new P4::ParseAnnotations("P4RuntimeDataTypeSpecTest", false, + { + {"p4runtime_translation", + &P4::ParseAnnotations::parseP4rtTranslationAnnotation}, + }), + new P4::ResolveReferences(&refMap), new P4::TypeInference(&refMap, &typeMap, false)}); pgm = pgm->apply(passes); return pgm; } template - const T* findExternTypeParameterName( - const IR::P4Program* program, cstring externName) const { - const T* type = nullptr; - forAllMatching(program, [&](const IR::Type_Specialized* ts) { + const T *findExternTypeParameterName(const IR::P4Program *program, cstring externName) const { + const T *type = nullptr; + forAllMatching(program, [&](const IR::Type_Specialized *ts) { if (ts->baseType->toString() != externName) return; ASSERT_TRUE(type == nullptr); ASSERT_TRUE(ts->arguments->at(0)->is()); @@ -1676,10 +1667,10 @@ TEST_F(P4RuntimeDataTypeSpec, Bits) { int size(9); bool isSigned(true); auto type = new IR::Type_Bits(size, isSigned); - auto typeSpec = P4::ControlPlaneAPI::TypeSpecConverter::convert( - &refMap, &typeMap, type, &typeInfo); + auto typeSpec = + P4::ControlPlaneAPI::TypeSpecConverter::convert(&refMap, &typeMap, type, &typeInfo); ASSERT_TRUE(typeSpec->has_bitstring()); - const auto& bitstringTypeSpec = typeSpec->bitstring(); + const auto &bitstringTypeSpec = typeSpec->bitstring(); ASSERT_TRUE(bitstringTypeSpec.has_int_()); // signed type EXPECT_EQ(size, bitstringTypeSpec.int_().bitwidth()); } @@ -1687,18 +1678,18 @@ TEST_F(P4RuntimeDataTypeSpec, Bits) { TEST_F(P4RuntimeDataTypeSpec, Varbits) { int size(64); auto type = new IR::Type_Varbits(size); - auto typeSpec = P4::ControlPlaneAPI::TypeSpecConverter::convert( - &refMap, &typeMap, type, &typeInfo); + auto typeSpec = + P4::ControlPlaneAPI::TypeSpecConverter::convert(&refMap, &typeMap, type, &typeInfo); ASSERT_TRUE(typeSpec->has_bitstring()); - const auto& bitstringTypeSpec = typeSpec->bitstring(); + const auto &bitstringTypeSpec = typeSpec->bitstring(); ASSERT_TRUE(bitstringTypeSpec.has_varbit()); EXPECT_EQ(size, bitstringTypeSpec.varbit().max_bitwidth()); } TEST_F(P4RuntimeDataTypeSpec, Boolean) { auto type = new IR::Type_Boolean(); - auto typeSpec = P4::ControlPlaneAPI::TypeSpecConverter::convert( - &refMap, &typeMap, type, &typeInfo); + auto typeSpec = + P4::ControlPlaneAPI::TypeSpecConverter::convert(&refMap, &typeMap, type, &typeInfo); EXPECT_TRUE(typeSpec->has_bool_()); } @@ -1707,19 +1698,19 @@ TEST_F(P4RuntimeDataTypeSpec, Tuple) { auto typeMember2 = new IR::Type_Bits(2, false); IR::Vector components = {typeMember1, typeMember2}; auto type = new IR::Type_Tuple(std::move(components)); - auto typeSpec = P4::ControlPlaneAPI::TypeSpecConverter::convert( - &refMap, &typeMap, type, &typeInfo); + auto typeSpec = + P4::ControlPlaneAPI::TypeSpecConverter::convert(&refMap, &typeMap, type, &typeInfo); ASSERT_TRUE(typeSpec->has_tuple()); - const auto& tupleTypeSpec = typeSpec->tuple(); + const auto &tupleTypeSpec = typeSpec->tuple(); ASSERT_EQ(2, tupleTypeSpec.members_size()); { - auto typeSpec = P4::ControlPlaneAPI::TypeSpecConverter::convert( - &refMap, &typeMap, typeMember1, nullptr); + auto typeSpec = P4::ControlPlaneAPI::TypeSpecConverter::convert(&refMap, &typeMap, + typeMember1, nullptr); EXPECT_TRUE(MessageDifferencer::Equals(*typeSpec, tupleTypeSpec.members(0))); } { - auto typeSpec = P4::ControlPlaneAPI::TypeSpecConverter::convert( - &refMap, &typeMap, typeMember2, nullptr); + auto typeSpec = P4::ControlPlaneAPI::TypeSpecConverter::convert(&refMap, &typeMap, + typeMember2, nullptr); EXPECT_TRUE(MessageDifferencer::Equals(*typeSpec, tupleTypeSpec.members(1))); } } @@ -1735,8 +1726,8 @@ TEST_F(P4RuntimeDataTypeSpec, Struct) { auto type = findExternTypeParameterName(pgm, "my_extern_t"); ASSERT_TRUE(type != nullptr); - auto typeSpec = P4::ControlPlaneAPI::TypeSpecConverter::convert( - &refMap, &typeMap, type, &typeInfo); + auto typeSpec = + P4::ControlPlaneAPI::TypeSpecConverter::convert(&refMap, &typeMap, type, &typeInfo); ASSERT_TRUE(typeSpec->has_struct_()); EXPECT_EQ("my_struct", typeSpec->struct_().name()); @@ -1761,8 +1752,8 @@ TEST_F(P4RuntimeDataTypeSpec, Header) { auto type = findExternTypeParameterName(pgm, "my_extern_t"); ASSERT_TRUE(type != nullptr); - auto typeSpec = P4::ControlPlaneAPI::TypeSpecConverter::convert( - &refMap, &typeMap, type, &typeInfo); + auto typeSpec = + P4::ControlPlaneAPI::TypeSpecConverter::convert(&refMap, &typeMap, type, &typeInfo); ASSERT_TRUE(typeSpec->has_header()); EXPECT_EQ("my_header", typeSpec->header().name()); @@ -1787,8 +1778,8 @@ TEST_F(P4RuntimeDataTypeSpec, HeaderWithFlattening) { auto type = findExternTypeParameterName(pgm, "my_extern_t"); ASSERT_TRUE(type != nullptr); - auto typeSpec = P4::ControlPlaneAPI::TypeSpecConverter::convert( - &refMap, &typeMap, type, &typeInfo); + auto typeSpec = + P4::ControlPlaneAPI::TypeSpecConverter::convert(&refMap, &typeMap, type, &typeInfo); ASSERT_TRUE(typeSpec->has_header()); EXPECT_EQ("my_header", typeSpec->header().name()); @@ -1816,8 +1807,8 @@ TEST_F(P4RuntimeDataTypeSpec, HeaderUnion) { auto type = findExternTypeParameterName(pgm, "my_extern_t"); ASSERT_TRUE(type != nullptr); - auto typeSpec = P4::ControlPlaneAPI::TypeSpecConverter::convert( - &refMap, &typeMap, type, &typeInfo); + auto typeSpec = + P4::ControlPlaneAPI::TypeSpecConverter::convert(&refMap, &typeMap, type, &typeInfo); ASSERT_TRUE(typeSpec->has_header_union()); EXPECT_EQ("my_header_union", typeSpec->header_union().name()); @@ -1846,8 +1837,8 @@ TEST_F(P4RuntimeDataTypeSpec, HeaderStack) { auto type = findExternTypeParameterName(pgm, "my_extern_t"); ASSERT_TRUE(type != nullptr); - auto typeSpec = P4::ControlPlaneAPI::TypeSpecConverter::convert( - &refMap, &typeMap, type, &typeInfo); + auto typeSpec = + P4::ControlPlaneAPI::TypeSpecConverter::convert(&refMap, &typeMap, type, &typeInfo); ASSERT_TRUE(typeSpec->has_header_stack()); EXPECT_EQ("my_header", typeSpec->header_stack().header().name()); EXPECT_EQ(3, typeSpec->header_stack().size()); @@ -1868,8 +1859,8 @@ TEST_F(P4RuntimeDataTypeSpec, HeaderUnionStack) { auto type = findExternTypeParameterName(pgm, "my_extern_t"); ASSERT_TRUE(type != nullptr); - auto typeSpec = P4::ControlPlaneAPI::TypeSpecConverter::convert( - &refMap, &typeMap, type, &typeInfo); + auto typeSpec = + P4::ControlPlaneAPI::TypeSpecConverter::convert(&refMap, &typeMap, type, &typeInfo); ASSERT_TRUE(typeSpec->has_header_union_stack()); EXPECT_EQ("my_header_union", typeSpec->header_union_stack().header_union().name()); EXPECT_EQ(3, typeSpec->header_union_stack().size()); @@ -1890,8 +1881,8 @@ TEST_F(P4RuntimeDataTypeSpec, Enum) { auto type = findExternTypeParameterName(pgm, "my_extern_t"); ASSERT_TRUE(type != nullptr); - auto typeSpec = P4::ControlPlaneAPI::TypeSpecConverter::convert( - &refMap, &typeMap, type, &typeInfo); + auto typeSpec = + P4::ControlPlaneAPI::TypeSpecConverter::convert(&refMap, &typeMap, type, &typeInfo); ASSERT_TRUE(typeSpec->has_enum_()); EXPECT_EQ("my_enum", typeSpec->enum_().name()); @@ -1913,8 +1904,8 @@ TEST_F(P4RuntimeDataTypeSpec, SerEnum) { auto type = findExternTypeParameterName(pgm, "my_extern_t"); ASSERT_TRUE(type != nullptr); - auto typeSpec = P4::ControlPlaneAPI::TypeSpecConverter::convert( - &refMap, &typeMap, type, &typeInfo); + auto typeSpec = + P4::ControlPlaneAPI::TypeSpecConverter::convert(&refMap, &typeMap, type, &typeInfo); ASSERT_TRUE(typeSpec->has_serializable_enum()); EXPECT_EQ("my_enum", typeSpec->serializable_enum().name()); @@ -1938,8 +1929,8 @@ TEST_F(P4RuntimeDataTypeSpec, Error) { auto type = findExternTypeParameterName(pgm, "my_extern_t"); ASSERT_TRUE(type != nullptr); - auto typeSpec = P4::ControlPlaneAPI::TypeSpecConverter::convert( - &refMap, &typeMap, type, &typeInfo); + auto typeSpec = + P4::ControlPlaneAPI::TypeSpecConverter::convert(&refMap, &typeMap, type, &typeInfo); ASSERT_TRUE(typeSpec->has_error()); ASSERT_TRUE(typeInfo.has_error()); @@ -1960,8 +1951,8 @@ TEST_F(P4RuntimeDataTypeSpec, StructWithTypedef) { auto type = findExternTypeParameterName(pgm, "my_extern_t"); ASSERT_TRUE(type != nullptr); - auto typeSpec = P4::ControlPlaneAPI::TypeSpecConverter::convert( - &refMap, &typeMap, type, &typeInfo); + auto typeSpec = + P4::ControlPlaneAPI::TypeSpecConverter::convert(&refMap, &typeMap, type, &typeInfo); ASSERT_TRUE(typeSpec->has_struct_()); EXPECT_EQ("my_struct", typeSpec->struct_().name()); @@ -1969,11 +1960,11 @@ TEST_F(P4RuntimeDataTypeSpec, StructWithTypedef) { ASSERT_TRUE(it != typeInfo.structs().end()); ASSERT_EQ(2, it->second.members_size()); auto check_member = [&](cstring name, int index) { - EXPECT_EQ(name, it->second.members(index).name()); - const auto &memberTypeSpec = it->second.members(index).type_spec(); - ASSERT_TRUE(memberTypeSpec.has_bitstring()); - ASSERT_TRUE(memberTypeSpec.bitstring().has_bit()); - EXPECT_EQ(8, memberTypeSpec.bitstring().bit().bitwidth()); + EXPECT_EQ(name, it->second.members(index).name()); + const auto &memberTypeSpec = it->second.members(index).type_spec(); + ASSERT_TRUE(memberTypeSpec.has_bitstring()); + ASSERT_TRUE(memberTypeSpec.bitstring().has_bit()); + EXPECT_EQ(8, memberTypeSpec.bitstring().bit().bitwidth()); }; check_member("f", 0); check_member("f2", 1); @@ -1993,8 +1984,8 @@ TEST_F(P4RuntimeDataTypeSpec, NewType) { auto type = findExternTypeParameterName(pgm, "my_extern_t"); ASSERT_TRUE(type != nullptr); - auto typeSpec = P4::ControlPlaneAPI::TypeSpecConverter::convert( - &refMap, &typeMap, type, &typeInfo); + auto typeSpec = + P4::ControlPlaneAPI::TypeSpecConverter::convert(&refMap, &typeMap, type, &typeInfo); ASSERT_TRUE(typeSpec->has_struct_()); EXPECT_EQ("my_struct", typeSpec->struct_().name()); @@ -2003,10 +1994,10 @@ TEST_F(P4RuntimeDataTypeSpec, NewType) { ASSERT_EQ(2, it->second.members_size()); auto check_member = [&](cstring memberName, int index, cstring newTypeName) { - EXPECT_EQ(memberName, it->second.members(index).name()); - const auto &memberTypeSpec = it->second.members(index).type_spec(); - ASSERT_TRUE(memberTypeSpec.has_new_type()); - EXPECT_EQ(newTypeName, memberTypeSpec.new_type().name()); + EXPECT_EQ(memberName, it->second.members(index).name()); + const auto &memberTypeSpec = it->second.members(index).type_spec(); + ASSERT_TRUE(memberTypeSpec.has_new_type()); + EXPECT_EQ(newTypeName, memberTypeSpec.new_type().name()); }; check_member("f", 0, "my_type_t"); check_member("f2", 1, "my_type2_t"); @@ -2068,8 +2059,7 @@ TEST_F(P4RuntimeDataTypeSpec, NewTypeIllegalTranslationAnnotations) { auto type = findExternTypeParameterName(pgm, "my_extern_t"); ASSERT_TRUE(type != nullptr); - P4::ControlPlaneAPI::TypeSpecConverter::convert( - &refMap, &typeMap, type, &typeInfo); + P4::ControlPlaneAPI::TypeSpecConverter::convert(&refMap, &typeMap, type, &typeInfo); EXPECT_EQ(1u, ::errorCount()); // But a type error. } @@ -2094,24 +2084,20 @@ TEST_F(P4RuntimeDataTypeSpec, NewTypeValidTranslationAnnotations) { auto type = findExternTypeParameterName(pgm, "my_extern_t"); ASSERT_TRUE(type != nullptr); - P4::ControlPlaneAPI::TypeSpecConverter::convert( - &refMap, &typeMap, type, &typeInfo); + P4::ControlPlaneAPI::TypeSpecConverter::convert(&refMap, &typeMap, type, &typeInfo); for (std::string type : {"my_type1_t", "my_type2_t", "my_type3_t"}) { auto it = typeInfo.new_types().find(type); ASSERT_TRUE(it != typeInfo.new_types().end()); - const P4NewTypeTranslation& translation = it->second.translated_type(); + const P4NewTypeTranslation &translation = it->second.translated_type(); EXPECT_EQ("p4.org/myArch/v1/Type", translation.uri()); if (type == "my_type3_t") { - EXPECT_EQ(translation.sdn_type_case(), - P4NewTypeTranslation::kSdnString); + EXPECT_EQ(translation.sdn_type_case(), P4NewTypeTranslation::kSdnString); } else { - EXPECT_EQ(translation.sdn_type_case(), - P4NewTypeTranslation::kSdnBitwidth); + EXPECT_EQ(translation.sdn_type_case(), P4NewTypeTranslation::kSdnBitwidth); EXPECT_EQ(translation.sdn_bitwidth(), 32); } } } - } // namespace Test diff --git a/test/gtest/parser_unroll.cpp b/test/gtest/parser_unroll.cpp index 3dff7a949f..986012dbaf 100644 --- a/test/gtest/parser_unroll.cpp +++ b/test/gtest/parser_unroll.cpp @@ -1,15 +1,7 @@ #include #include - -#include "test/gtest/env.h" -#include "test/gtest/helpers.h" -#include "gtest/gtest.h" -#include "ir/ir.h" -#include "lib/log.h" - #include "backends/p4test/version.h" - #include "frontends/common/constantFolding.h" #include "frontends/common/parseInput.h" #include "frontends/common/resolveReferences/resolveReferences.h" @@ -18,40 +10,45 @@ #include "frontends/p4/fromv1.0/v1model.h" #include "frontends/p4/moveDeclarations.h" #include "frontends/p4/simplify.h" -#include "frontends/p4/typeChecking/typeChecker.h" #include "frontends/p4/simplifyParsers.h" #include "frontends/p4/strengthReduction.h" #include "frontends/p4/toP4/toP4.h" +#include "frontends/p4/typeChecking/typeChecker.h" #include "frontends/p4/typeMap.h" #include "frontends/p4/uniqueNames.h" #include "frontends/p4/unusedDeclarations.h" +#include "gtest/gtest.h" +#include "ir/ir.h" +#include "lib/log.h" #include "midend/actionSynthesis.h" #include "midend/compileTimeOps.h" #include "midend/complexComparison.h" #include "midend/copyStructures.h" -#include "midend/eliminateTuples.h" #include "midend/eliminateNewtype.h" #include "midend/eliminateSerEnums.h" #include "midend/eliminateSwitch.h" -#include "midend/flattenHeaders.h" -#include "midend/flattenInterfaceStructs.h" -#include "midend/replaceSelectRange.h" +#include "midend/eliminateTuples.h" #include "midend/expandEmit.h" #include "midend/expandLookahead.h" +#include "midend/flattenHeaders.h" +#include "midend/flattenInterfaceStructs.h" #include "midend/local_copyprop.h" #include "midend/midEndLast.h" #include "midend/nestedStructs.h" #include "midend/noMatch.h" +#include "midend/parserUnroll.h" #include "midend/predication.h" +#include "midend/removeAssertAssume.h" #include "midend/removeExits.h" #include "midend/removeMiss.h" #include "midend/removeSelectBooleans.h" +#include "midend/replaceSelectRange.h" #include "midend/simplifyKey.h" #include "midend/simplifySelectCases.h" #include "midend/simplifySelectList.h" #include "midend/tableHit.h" -#include "midend/removeAssertAssume.h" -#include "midend/parserUnroll.h" +#include "test/gtest/env.h" +#include "test/gtest/helpers.h" using namespace P4; @@ -59,35 +56,31 @@ namespace Test { class P4TestOptions : public CompilerOptions { public: - P4TestOptions() { - } + P4TestOptions() {} }; using P4TestContext = P4CContextWithOptions; -class P4CParserUnroll : public P4CTest { }; - +class P4CParserUnroll : public P4CTest {}; class SkipControls : public P4::ActionSynthesisPolicy { const std::set *skip; public: explicit SkipControls(const std::set *skip) : skip(skip) { CHECK_NULL(skip); } - bool convert(const Visitor::Context *, const IR::P4Control* control) override { - if (skip->find(control->name) != skip->end()) - return false; + bool convert(const Visitor::Context *, const IR::P4Control *control) override { + if (skip->find(control->name) != skip->end()) return false; return true; } }; - class MidEnd : public PassManager { public: - P4::ReferenceMap refMap; - P4::TypeMap typeMap; - IR::ToplevelBlock *toplevel = nullptr; + P4::ReferenceMap refMap; + P4::TypeMap typeMap; + IR::ToplevelBlock *toplevel = nullptr; - explicit MidEnd(CompilerOptions& options, std::ostream* outStream = nullptr) { + explicit MidEnd(CompilerOptions &options, std::ostream *outStream = nullptr) { bool isv1 = options.langVersion == CompilerOptions::FrontendVersion::P4_14; refMap.setIsV1(isv1); auto evaluator = new P4::EvaluatorPass(&refMap, &typeMap); @@ -95,78 +88,73 @@ class MidEnd : public PassManager { auto v1controls = new std::set(); - addPasses({ - options.ndebug ? new P4::RemoveAssertAssume(&refMap, &typeMap) : nullptr, - new P4::RemoveMiss(&refMap, &typeMap), - new P4::EliminateNewtype(&refMap, &typeMap), - new P4::EliminateSerEnums(&refMap, &typeMap), - new P4::SimplifyKey(&refMap, &typeMap, - new P4::OrPolicy( - new P4::IsValid(&refMap, &typeMap), - new P4::IsLikeLeftValue())), - new P4::RemoveExits(&refMap, &typeMap), - new P4::ConstantFolding(&refMap, &typeMap), - new P4::SimplifySelectCases(&refMap, &typeMap, false), // non-constant keysets - new P4::ExpandLookahead(&refMap, &typeMap), - new P4::ExpandEmit(&refMap, &typeMap), - new P4::HandleNoMatch(&refMap), - new P4::SimplifyParsers(&refMap), - new P4::StrengthReduction(&refMap, &typeMap), - new P4::EliminateTuples(&refMap, &typeMap), - new P4::SimplifyComparisons(&refMap, &typeMap), - new P4::CopyStructures(&refMap, &typeMap), - new P4::NestedStructs(&refMap, &typeMap), - new P4::SimplifySelectList(&refMap, &typeMap), - new P4::RemoveSelectBooleans(&refMap, &typeMap), - new P4::FlattenHeaders(&refMap, &typeMap), - new P4::FlattenInterfaceStructs(&refMap, &typeMap), - new P4::ReplaceSelectRange(&refMap, &typeMap), - new P4::Predication(&refMap), - new P4::MoveDeclarations(), // more may have been introduced - new P4::ConstantFolding(&refMap, &typeMap), - new P4::LocalCopyPropagation(&refMap, &typeMap), - new P4::ConstantFolding(&refMap, &typeMap), - new P4::StrengthReduction(&refMap, &typeMap), - new P4::MoveDeclarations(), // more may have been introduced - new P4::SimplifyControlFlow(&refMap, &typeMap), - new P4::CompileTimeOperations(), - new P4::TableHit(&refMap, &typeMap), - new P4::EliminateSwitch(&refMap, &typeMap), - evaluator, - [v1controls, evaluator](const IR::Node *root) -> const IR::Node * { - auto toplevel = evaluator->getToplevelBlock(); - auto main = toplevel->getMain(); - if (main == nullptr) - // nothing further to do - return nullptr; - // Special handling when compiling for v1model.p4 - if (main->type->name == P4V1::V1Model::instance.sw.name) { - if (main->getConstructorParameters()->size() != 6) - return root; - auto verify = main->getParameterValue(P4V1::V1Model::instance.sw.verify.name); - auto update = main->getParameterValue( - P4V1::V1Model::instance.sw.compute.name); - auto deparser = main->getParameterValue( - P4V1::V1Model::instance.sw.deparser.name); - if (verify == nullptr || update == nullptr || deparser == nullptr || - !verify->is() || !update->is() || - !deparser->is()) { - return root; - } - v1controls->emplace(verify->to()->container->name); - v1controls->emplace(update->to()->container->name); - v1controls->emplace(deparser->to()->container->name); - } - return root; }, - new P4::SynthesizeActions(&refMap, &typeMap, new SkipControls(v1controls)), - new P4::MoveActionsToTables(&refMap, &typeMap), - options.loopsUnrolling ? new ParsersUnroll(true, &refMap, &typeMap) : nullptr, - evaluator, - [this, evaluator]() { - toplevel = evaluator->getToplevelBlock(); - }, - new P4::MidEndLast() - }); + addPasses( + {options.ndebug ? new P4::RemoveAssertAssume(&refMap, &typeMap) : nullptr, + new P4::RemoveMiss(&refMap, &typeMap), + new P4::EliminateNewtype(&refMap, &typeMap), + new P4::EliminateSerEnums(&refMap, &typeMap), + new P4::SimplifyKey( + &refMap, &typeMap, + new P4::OrPolicy(new P4::IsValid(&refMap, &typeMap), new P4::IsLikeLeftValue())), + new P4::RemoveExits(&refMap, &typeMap), + new P4::ConstantFolding(&refMap, &typeMap), + new P4::SimplifySelectCases(&refMap, &typeMap, false), // non-constant keysets + new P4::ExpandLookahead(&refMap, &typeMap), + new P4::ExpandEmit(&refMap, &typeMap), + new P4::HandleNoMatch(&refMap), + new P4::SimplifyParsers(&refMap), + new P4::StrengthReduction(&refMap, &typeMap), + new P4::EliminateTuples(&refMap, &typeMap), + new P4::SimplifyComparisons(&refMap, &typeMap), + new P4::CopyStructures(&refMap, &typeMap), + new P4::NestedStructs(&refMap, &typeMap), + new P4::SimplifySelectList(&refMap, &typeMap), + new P4::RemoveSelectBooleans(&refMap, &typeMap), + new P4::FlattenHeaders(&refMap, &typeMap), + new P4::FlattenInterfaceStructs(&refMap, &typeMap), + new P4::ReplaceSelectRange(&refMap, &typeMap), + new P4::Predication(&refMap), + new P4::MoveDeclarations(), // more may have been introduced + new P4::ConstantFolding(&refMap, &typeMap), + new P4::LocalCopyPropagation(&refMap, &typeMap), + new P4::ConstantFolding(&refMap, &typeMap), + new P4::StrengthReduction(&refMap, &typeMap), + new P4::MoveDeclarations(), // more may have been introduced + new P4::SimplifyControlFlow(&refMap, &typeMap), + new P4::CompileTimeOperations(), + new P4::TableHit(&refMap, &typeMap), + new P4::EliminateSwitch(&refMap, &typeMap), + evaluator, + [v1controls, evaluator](const IR::Node *root) -> const IR::Node * { + auto toplevel = evaluator->getToplevelBlock(); + auto main = toplevel->getMain(); + if (main == nullptr) + // nothing further to do + return nullptr; + // Special handling when compiling for v1model.p4 + if (main->type->name == P4V1::V1Model::instance.sw.name) { + if (main->getConstructorParameters()->size() != 6) return root; + auto verify = main->getParameterValue(P4V1::V1Model::instance.sw.verify.name); + auto update = main->getParameterValue(P4V1::V1Model::instance.sw.compute.name); + auto deparser = + main->getParameterValue(P4V1::V1Model::instance.sw.deparser.name); + if (verify == nullptr || update == nullptr || deparser == nullptr || + !verify->is() || !update->is() || + !deparser->is()) { + return root; + } + v1controls->emplace(verify->to()->container->name); + v1controls->emplace(update->to()->container->name); + v1controls->emplace(deparser->to()->container->name); + } + return root; + }, + new P4::SynthesizeActions(&refMap, &typeMap, new SkipControls(v1controls)), + new P4::MoveActionsToTables(&refMap, &typeMap), + options.loopsUnrolling ? new ParsersUnroll(true, &refMap, &typeMap) : nullptr, + evaluator, + [this, evaluator]() { toplevel = evaluator->getToplevelBlock(); }, + new P4::MidEndLast()}); if (options.listMidendPasses) { listPasses(*outStream, "\n"); *outStream << std::endl; @@ -177,43 +165,45 @@ class MidEnd : public PassManager { } toplevel = evaluator->getToplevelBlock(); } - IR::ToplevelBlock* process(const IR::P4Program *&program) { + IR::ToplevelBlock *process(const IR::P4Program *&program) { program = program->apply(*this); - return toplevel; } + return toplevel; + } }; // #define PARSER_UNROLL_TIME_CHECKING #ifdef PARSER_UNROLL_TIME_CHECKING - #include +#include #endif -const IR::P4Parser* getParser(const IR::P4Program* program) { - std::function filter = - [](const IR::IDeclaration* d) - { CHECK_NULL(d); return d->is(); }; - const auto* newDeclVector = program->getDeclarations()->where(filter)->toVector(); +const IR::P4Parser *getParser(const IR::P4Program *program) { + std::function filter = [](const IR::IDeclaration *d) { + CHECK_NULL(d); + return d->is(); + }; + const auto *newDeclVector = program->getDeclarations()->where(filter)->toVector(); return (*newDeclVector)[0]->to(); } /// Rewrites parser -std::pair rewriteParser(const IR::P4Program* program, - CompilerOptions& options) { +std::pair rewriteParser(const IR::P4Program *program, + CompilerOptions &options) { P4::FrontEnd frontend; program = frontend.run(options, program); CHECK_NULL(program); - P4::ReferenceMap refMap; - P4::TypeMap typeMap; + P4::ReferenceMap refMap; + P4::TypeMap typeMap; #ifdef PARSER_UNROLL_TIME_CHECKING - using std::chrono::high_resolution_clock; - using std::chrono::duration_cast; using std::chrono::duration; + using std::chrono::duration_cast; + using std::chrono::high_resolution_clock; using std::chrono::milliseconds; auto t1 = high_resolution_clock::now(); #endif MidEnd midEnd(options); - const IR::P4Program* res = program; + const IR::P4Program *res = program; midEnd.process(res); #ifdef PARSER_UNROLL_TIME_CHECKING auto t2 = high_resolution_clock::now(); @@ -224,7 +214,7 @@ std::pair rewriteParser(const IR::P4Pr } /// Loads example from a file -const IR::P4Program* load_model(const char* curFile, CompilerOptions& options) { +const IR::P4Program *load_model(const char *curFile, CompilerOptions &options) { std::string includeDir = std::string(buildPath) + std::string("p4include"); auto originalEnv = getenv("P4C_16_INCLUDE_PATH"); setenv("P4C_16_INCLUDE_PATH", includeDir.c_str(), 1); @@ -241,17 +231,16 @@ const IR::P4Program* load_model(const char* curFile, CompilerOptions& options) { return program; } -std::pair loadExample(const char *file, - CompilerOptions::FrontendVersion langVersion = - CompilerOptions::FrontendVersion::P4_16) { +std::pair loadExample( + const char *file, + CompilerOptions::FrontendVersion langVersion = CompilerOptions::FrontendVersion::P4_16) { AutoCompileContext autoP4TestContext(new P4TestContext); - auto& options = P4TestContext::get().options(); - const char* argv = "./gtestp4c"; - options.process(1, (char* const*)&argv); + auto &options = P4TestContext::get().options(); + const char *argv = "./gtestp4c"; + options.process(1, (char *const *)&argv); options.langVersion = langVersion; - const IR::P4Program* program = load_model(file, options); - if (!program) - return std::make_pair(nullptr, nullptr); + const IR::P4Program *program = load_model(file, options); + if (!program) return std::make_pair(nullptr, nullptr); return rewriteParser(program, options); } @@ -268,7 +257,7 @@ TEST_F(P4CParserUnroll, test2) { auto parsers = loadExample("parser-unroll-test2.p4"); ASSERT_TRUE(parsers.first); ASSERT_TRUE(parsers.second); - ASSERT_EQ(parsers.first->states.size(), parsers.second->states.size() - 3 - 1); + ASSERT_EQ(parsers.first->states.size(), parsers.second->states.size() - 3 - 1); } TEST_F(P4CParserUnroll, test3) { @@ -279,36 +268,36 @@ TEST_F(P4CParserUnroll, test3) { } TEST_F(P4CParserUnroll, switch_20160512) { - auto parsers = loadExample("../p4_14_samples/switch_20160512/switch.p4", - CompilerOptions::FrontendVersion::P4_14); + auto parsers = loadExample("../p4_14_samples/switch_20160512/switch.p4", + CompilerOptions::FrontendVersion::P4_14); ASSERT_TRUE(parsers.first); ASSERT_TRUE(parsers.second); ASSERT_EQ(parsers.first->states.size(), parsers.second->states.size() - 22 - 4 - 2); } TEST_F(P4CParserUnroll, header_stack_access_remover) { - auto parsers = loadExample("parser-unroll-test4.p4"); + auto parsers = loadExample("parser-unroll-test4.p4"); ASSERT_TRUE(parsers.first); ASSERT_TRUE(parsers.second); ASSERT_EQ(parsers.first->states.size(), parsers.second->states.size() - 3); } TEST_F(P4CParserUnroll, noLoopsAndHeaderStacks) { - auto parsers = loadExample("parser-unroll-test5.p4"); + auto parsers = loadExample("parser-unroll-test5.p4"); ASSERT_TRUE(parsers.first); ASSERT_TRUE(parsers.second); ASSERT_EQ(parsers.first->states.size(), parsers.second->states.size()); } TEST_F(P4CParserUnroll, t1_Cond) { - auto parsers = loadExample("parser-unroll-t1-cond.p4"); + auto parsers = loadExample("parser-unroll-t1-cond.p4"); ASSERT_TRUE(parsers.first); ASSERT_TRUE(parsers.second); ASSERT_EQ(parsers.first->states.size(), parsers.second->states.size()); } TEST_F(P4CParserUnroll, header_union) { - auto parsers = loadExample("issue561-7-bmv2.p4"); + auto parsers = loadExample("issue561-7-bmv2.p4"); ASSERT_TRUE(parsers.first); ASSERT_TRUE(parsers.second); ASSERT_EQ(parsers.first->states.size(), parsers.second->states.size()); diff --git a/test/gtest/path_test.cpp b/test/gtest/path_test.cpp index 5671865bc9..65c7c5e570 100644 --- a/test/gtest/path_test.cpp +++ b/test/gtest/path_test.cpp @@ -1,5 +1,5 @@ /* -Copyright 2013-present Barefoot Networks, Inc. +Copyright 2013-present Barefoot Networks, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,8 +14,9 @@ See the License for the specific language governing permissions and limitations under the License. */ -#include "gtest/gtest.h" #include "lib/path.h" + +#include "gtest/gtest.h" #include "lib/exceptions.h" #include "lib/stringref.h" diff --git a/test/gtest/source_file_test.cpp b/test/gtest/source_file_test.cpp index deac98b762..7840df92ec 100644 --- a/test/gtest/source_file_test.cpp +++ b/test/gtest/source_file_test.cpp @@ -14,11 +14,12 @@ See the License for the specific language governing permissions and limitations under the License. */ +#include "lib/source_file.h" + #include "gtest/gtest.h" +#include "lib/compile_context.h" #include "lib/cstring.h" #include "lib/exceptions.h" -#include "lib/source_file.h" -#include "lib/compile_context.h" namespace Util { @@ -29,7 +30,7 @@ TEST(UtilSourceFile, SourcePosition) { SourcePosition position(3, 3); EXPECT_EQ("3:3", position.toString()); - auto& context = BaseCompileContext::get(); + auto &context = BaseCompileContext::get(); cstring str = context.errorReporter().format_message("%1% - %2%", position, position); EXPECT_EQ("3:3 - 3:3\n", str); diff --git a/test/gtest/stringify.cpp b/test/gtest/stringify.cpp index 692b7af0ce..e933b0ba9b 100644 --- a/test/gtest/stringify.cpp +++ b/test/gtest/stringify.cpp @@ -13,13 +13,15 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ +#include "lib/stringify.h" + #include + #include "gtest/gtest.h" -#include "lib/stringify.h" #include "lib/cstring.h" namespace Test { -cstring appendFormat(const char* format, ...) { +cstring appendFormat(const char *format, ...) { va_list ap; va_start(ap, format); cstring str = Util::vprintf_format(format, ap); diff --git a/test/gtest/transforms.cpp b/test/gtest/transforms.cpp index 58925cae2a..301d7493ae 100644 --- a/test/gtest/transforms.cpp +++ b/test/gtest/transforms.cpp @@ -1,5 +1,5 @@ /* -Copyright 2013-present Barefoot Networks, Inc. +Copyright 2013-present Barefoot Networks, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -22,24 +22,24 @@ limitations under the License. namespace Test { -class P4C_IR : public P4CTest { }; +class P4C_IR : public P4CTest {}; TEST_F(P4C_IR, Transform) { struct TestTrans : public Transform { - explicit TestTrans(IR::Constant* c) : c(c) { } + explicit TestTrans(IR::Constant *c) : c(c) {} - IR::Node* postorder(IR::Add* a) override { + IR::Node *postorder(IR::Add *a) override { EXPECT_EQ(c, a->left); EXPECT_EQ(c, a->right); return a; } - IR::Constant* c; + IR::Constant *c; }; auto c = new IR::Constant(2); - IR::Expression* e = new IR::Add(Util::SourceInfo(), c, c); - auto* n = e->apply(TestTrans(c)); + IR::Expression *e = new IR::Add(Util::SourceInfo(), c, c); + auto *n = e->apply(TestTrans(c)); EXPECT_EQ(e, n); }