[SyntaxTree] Implement annotation-based test infrastructure
authorEduardo Caldas <ecaldas@google.com>
Fri, 14 Aug 2020 09:43:20 +0000 (09:43 +0000)
committerEduardo Caldas <ecaldas@google.com>
Tue, 18 Aug 2020 13:00:56 +0000 (13:00 +0000)
We add the method `SyntaxTreeTest::treeDumpEqualOnAnnotations`, which
allows us to compare the treeDump of only annotated code. This will reduce a
lot of noise from our `BuildTreeTest` and make them short and easier to
read.

clang/unittests/Tooling/Syntax/TreeTestBase.cpp
clang/unittests/Tooling/Syntax/TreeTestBase.h

index 6d2efea..05fbac4 100644 (file)
@@ -180,6 +180,35 @@ SyntaxTreeTest::buildTree(StringRef Code, const TestClangConfig &ClangConfig) {
   return ::testing::AssertionSuccess();
 }
 
+::testing::AssertionResult
+SyntaxTreeTest::treeDumpEqualOnAnnotations(StringRef CodeWithAnnotations,
+                                           ArrayRef<StringRef> TreeDumps) {
+  SCOPED_TRACE(llvm::join(GetParam().getCommandLineArgs(), " "));
+
+  auto AnnotatedCode = llvm::Annotations(CodeWithAnnotations);
+  auto *Root = buildTree(AnnotatedCode.code(), GetParam());
+
+  if (Diags->getClient()->getNumErrors() != 0) {
+    return ::testing::AssertionFailure()
+           << "Source file has syntax errors, they were printed to the test "
+              "log";
+  }
+
+  bool failed = false;
+  auto AnnotatedRanges = AnnotatedCode.ranges();
+  assert(AnnotatedRanges.size() == TreeDumps.size());
+  for (auto i = 0ul; i < AnnotatedRanges.size(); i++) {
+    auto *AnnotatedNode = nodeByRange(AnnotatedRanges[i], Root);
+    assert(AnnotatedNode);
+    auto AnnotatedNodeDump =
+        std::string(StringRef(AnnotatedNode->dump(*Arena)).trim());
+    // EXPECT_EQ shows the diff between the two strings if they are different.
+    EXPECT_EQ(TreeDumps[i].trim().str(), AnnotatedNodeDump);
+    if (AnnotatedNodeDump != TreeDumps[i].trim().str())
+      failed = true;
+  }
+  return failed ? ::testing::AssertionFailure() : ::testing::AssertionSuccess();
+}
 syntax::Node *SyntaxTreeTest::nodeByRange(llvm::Annotations::Range R,
                                           syntax::Node *Root) {
   ArrayRef<syntax::Token> Toks = tokens(Root);
index bfa6ecd..c282bbf 100644 (file)
@@ -34,6 +34,9 @@ protected:
 
   ::testing::AssertionResult treeDumpEqual(StringRef Code, StringRef Tree);
 
+  ::testing::AssertionResult
+  treeDumpEqualOnAnnotations(StringRef CodeWithAnnotations,
+                             ArrayRef<StringRef> TreeDumps);
   /// Finds the deepest node in the tree that covers exactly \p R.
   /// FIXME: implement this efficiently and move to public syntax tree API.
   syntax::Node *nodeByRange(llvm::Annotations::Range R, syntax::Node *Root);