StencilTest.cpp 14.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
//===- unittest/Tooling/StencilTest.cpp -----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "clang/Tooling/Transformer/Stencil.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Tooling/FixIt.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/Support/Error.h"
#include "llvm/Testing/Support/Error.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"

using namespace clang;
using namespace transformer;
using namespace ast_matchers;

namespace {
using ::llvm::Failed;
using ::llvm::HasValue;
using ::llvm::StringError;
using ::testing::AllOf;
using ::testing::HasSubstr;
using MatchResult = MatchFinder::MatchResult;

// Create a valid translation-unit from a statement.
static std::string wrapSnippet(StringRef StatementCode) {
  return ("struct S { int field; }; auto stencil_test_snippet = []{" +
          StatementCode + "};")
      .str();
}

static DeclarationMatcher wrapMatcher(const StatementMatcher &Matcher) {
  return varDecl(hasName("stencil_test_snippet"),
                 hasDescendant(compoundStmt(hasAnySubstatement(Matcher))));
}

struct TestMatch {
  // The AST unit from which `result` is built. We bundle it because it backs
  // the result. Users are not expected to access it.
  std::unique_ptr<ASTUnit> AstUnit;
  // The result to use in the test. References `ast_unit`.
  MatchResult Result;
};

// Matches `Matcher` against the statement `StatementCode` and returns the
// result. Handles putting the statement inside a function and modifying the
// matcher correspondingly. `Matcher` should match one of the statements in
// `StatementCode` exactly -- that is, produce exactly one match. However,
// `StatementCode` may contain other statements not described by `Matcher`.
static llvm::Optional<TestMatch> matchStmt(StringRef StatementCode,
                                           StatementMatcher Matcher) {
  auto AstUnit = tooling::buildASTFromCode(wrapSnippet(StatementCode));
  if (AstUnit == nullptr) {
    ADD_FAILURE() << "AST construction failed";
    return llvm::None;
  }
  ASTContext &Context = AstUnit->getASTContext();
  auto Matches = ast_matchers::match(wrapMatcher(Matcher), Context);
  // We expect a single, exact match for the statement.
  if (Matches.size() != 1) {
    ADD_FAILURE() << "Wrong number of matches: " << Matches.size();
    return llvm::None;
  }
  return TestMatch{std::move(AstUnit), MatchResult(Matches[0], &Context)};
}

class StencilTest : public ::testing::Test {
protected:
  // Verifies that the given stencil fails when evaluated on a valid match
  // result. Binds a statement to "stmt", a (non-member) ctor-initializer to
  // "init", an expression to "expr" and a (nameless) declaration to "decl".
  void testError(const Stencil &Stencil,
                 ::testing::Matcher<std::string> Matcher) {
    const std::string Snippet = R"cc(
      struct A {};
      class F : public A {
       public:
        F(int) {}
      };
      F(1);
    )cc";
    auto StmtMatch = matchStmt(
        Snippet,
        stmt(hasDescendant(
                 cxxConstructExpr(
                     hasDeclaration(decl(hasDescendant(cxxCtorInitializer(
                                                           isBaseInitializer())
                                                           .bind("init")))
                                        .bind("decl")))
                     .bind("expr")))
            .bind("stmt"));
    ASSERT_TRUE(StmtMatch);
    if (auto ResultOrErr = Stencil->eval(StmtMatch->Result)) {
      ADD_FAILURE() << "Expected failure but succeeded: " << *ResultOrErr;
    } else {
      auto Err = llvm::handleErrors(ResultOrErr.takeError(),
                                    [&Matcher](const StringError &Err) {
                                      EXPECT_THAT(Err.getMessage(), Matcher);
                                    });
      if (Err) {
        ADD_FAILURE() << "Unhandled error: " << llvm::toString(std::move(Err));
      }
    }
  }

  // Tests failures caused by references to unbound nodes. `unbound_id` is the
  // id that will cause the failure.
  void testUnboundNodeError(const Stencil &Stencil, StringRef UnboundId) {
    testError(Stencil, AllOf(HasSubstr(UnboundId), HasSubstr("not bound")));
  }
};

TEST_F(StencilTest, SingleStatement) {
  StringRef Condition("C"), Then("T"), Else("E");
  const std::string Snippet = R"cc(
    if (true)
      return 1;
    else
      return 0;
  )cc";
  auto StmtMatch = matchStmt(
      Snippet, ifStmt(hasCondition(expr().bind(Condition)),
                      hasThen(stmt().bind(Then)), hasElse(stmt().bind(Else))));
  ASSERT_TRUE(StmtMatch);
  // Invert the if-then-else.
  auto Stencil = cat("if (!", node(Condition), ") ", statement(Else), " else ",
                     statement(Then));
  EXPECT_THAT_EXPECTED(Stencil->eval(StmtMatch->Result),
                       HasValue("if (!true) return 0; else return 1;"));
}

TEST_F(StencilTest, UnboundNode) {
  const std::string Snippet = R"cc(
    if (true)
      return 1;
    else
      return 0;
  )cc";
  auto StmtMatch = matchStmt(Snippet, ifStmt(hasCondition(stmt().bind("a1")),
                                             hasThen(stmt().bind("a2"))));
  ASSERT_TRUE(StmtMatch);
  auto Stencil = cat("if(!", node("a1"), ") ", node("UNBOUND"), ";");
  auto ResultOrErr = Stencil->eval(StmtMatch->Result);
  EXPECT_TRUE(llvm::errorToBool(ResultOrErr.takeError()))
      << "Expected unbound node, got " << *ResultOrErr;
}

// Tests that a stencil with a single parameter (`Id`) evaluates to the expected
// string, when `Id` is bound to the expression-statement in `Snippet`.
void testExpr(StringRef Id, StringRef Snippet, const Stencil &Stencil,
              StringRef Expected) {
  auto StmtMatch = matchStmt(Snippet, expr().bind(Id));
  ASSERT_TRUE(StmtMatch);
  EXPECT_THAT_EXPECTED(Stencil->eval(StmtMatch->Result), HasValue(Expected));
}

void testFailure(StringRef Id, StringRef Snippet, const Stencil &Stencil,
                 testing::Matcher<std::string> MessageMatcher) {
  auto StmtMatch = matchStmt(Snippet, expr().bind(Id));
  ASSERT_TRUE(StmtMatch);
  EXPECT_THAT_EXPECTED(Stencil->eval(StmtMatch->Result),
                       Failed<StringError>(testing::Property(
                           &StringError::getMessage, MessageMatcher)));
}

TEST_F(StencilTest, SelectionOp) {
  StringRef Id = "id";
  testExpr(Id, "3;", cat(node(Id)), "3");
}

TEST_F(StencilTest, IfBoundOpBound) {
  StringRef Id = "id";
  testExpr(Id, "3;", ifBound(Id, text("5"), text("7")), "5");
}

TEST_F(StencilTest, IfBoundOpUnbound) {
  StringRef Id = "id";
  testExpr(Id, "3;", ifBound("other", text("5"), text("7")), "7");
}

TEST_F(StencilTest, ExpressionOpNoParens) {
  StringRef Id = "id";
  testExpr(Id, "3;", expression(Id), "3");
}

// Don't parenthesize a parens expression.
TEST_F(StencilTest, ExpressionOpNoParensParens) {
  StringRef Id = "id";
  testExpr(Id, "(3);", expression(Id), "(3)");
}

TEST_F(StencilTest, ExpressionOpBinaryOpParens) {
  StringRef Id = "id";
  testExpr(Id, "3+4;", expression(Id), "(3+4)");
}

// `expression` shares code with other ops, so we get sufficient coverage of the
// error handling code with this test. If that changes in the future, more error
// tests should be added.
TEST_F(StencilTest, ExpressionOpUnbound) {
  StringRef Id = "id";
  testFailure(Id, "3;", expression("ACACA"),
              AllOf(HasSubstr("ACACA"), HasSubstr("not bound")));
}

TEST_F(StencilTest, DerefPointer) {
  StringRef Id = "id";
  testExpr(Id, "int *x; x;", deref(Id), "*x");
}

TEST_F(StencilTest, DerefBinOp) {
  StringRef Id = "id";
  testExpr(Id, "int *x; x + 1;", deref(Id), "*(x + 1)");
}

TEST_F(StencilTest, DerefAddressExpr) {
  StringRef Id = "id";
  testExpr(Id, "int x; &x;", deref(Id), "x");
}

TEST_F(StencilTest, AddressOfValue) {
  StringRef Id = "id";
  testExpr(Id, "int x; x;", addressOf(Id), "&x");
}

TEST_F(StencilTest, AddressOfDerefExpr) {
  StringRef Id = "id";
  testExpr(Id, "int *x; *x;", addressOf(Id), "x");
}

TEST_F(StencilTest, MaybeDerefValue) {
  StringRef Id = "id";
  testExpr(Id, "int x; x;", maybeDeref(Id), "x");
}

TEST_F(StencilTest, MaybeDerefPointer) {
  StringRef Id = "id";
  testExpr(Id, "int *x; x;", maybeDeref(Id), "*x");
}

TEST_F(StencilTest, MaybeDerefBinOp) {
  StringRef Id = "id";
  testExpr(Id, "int *x; x + 1;", maybeDeref(Id), "*(x + 1)");
}

TEST_F(StencilTest, MaybeDerefAddressExpr) {
  StringRef Id = "id";
  testExpr(Id, "int x; &x;", maybeDeref(Id), "x");
}

TEST_F(StencilTest, MaybeAddressOfPointer) {
  StringRef Id = "id";
  testExpr(Id, "int *x; x;", maybeAddressOf(Id), "x");
}

TEST_F(StencilTest, MaybeAddressOfValue) {
  StringRef Id = "id";
  testExpr(Id, "int x; x;", addressOf(Id), "&x");
}

TEST_F(StencilTest, MaybeAddressOfBinOp) {
  StringRef Id = "id";
  testExpr(Id, "int x; x + 1;", maybeAddressOf(Id), "&(x + 1)");
}

TEST_F(StencilTest, MaybeAddressOfDerefExpr) {
  StringRef Id = "id";
  testExpr(Id, "int *x; *x;", addressOf(Id), "x");
}

TEST_F(StencilTest, AccessOpValue) {
  StringRef Snippet = R"cc(
    S x;
    x;
  )cc";
  StringRef Id = "id";
  testExpr(Id, Snippet, access(Id, "field"), "x.field");
}

TEST_F(StencilTest, AccessOpValueExplicitText) {
  StringRef Snippet = R"cc(
    S x;
    x;
  )cc";
  StringRef Id = "id";
  testExpr(Id, Snippet, access(Id, text("field")), "x.field");
}

TEST_F(StencilTest, AccessOpValueAddress) {
  StringRef Snippet = R"cc(
    S x;
    &x;
  )cc";
  StringRef Id = "id";
  testExpr(Id, Snippet, access(Id, "field"), "x.field");
}

TEST_F(StencilTest, AccessOpPointer) {
  StringRef Snippet = R"cc(
    S *x;
    x;
  )cc";
  StringRef Id = "id";
  testExpr(Id, Snippet, access(Id, "field"), "x->field");
}

TEST_F(StencilTest, AccessOpPointerDereference) {
  StringRef Snippet = R"cc(
    S *x;
    *x;
  )cc";
  StringRef Id = "id";
  testExpr(Id, Snippet, access(Id, "field"), "x->field");
}

TEST_F(StencilTest, AccessOpExplicitThis) {
  using clang::ast_matchers::hasObjectExpression;
  using clang::ast_matchers::memberExpr;

  // Set up the code so we can bind to a use of this.
  StringRef Snippet = R"cc(
    class C {
     public:
      int x;
      int foo() { return this->x; }
    };
  )cc";
  auto StmtMatch =
      matchStmt(Snippet, returnStmt(hasReturnValue(ignoringImplicit(memberExpr(
                             hasObjectExpression(expr().bind("obj")))))));
  ASSERT_TRUE(StmtMatch);
  const Stencil Stencil = access("obj", "field");
  EXPECT_THAT_EXPECTED(Stencil->eval(StmtMatch->Result),
                       HasValue("this->field"));
}

TEST_F(StencilTest, AccessOpImplicitThis) {
  using clang::ast_matchers::hasObjectExpression;
  using clang::ast_matchers::memberExpr;

  // Set up the code so we can bind to a use of (implicit) this.
  StringRef Snippet = R"cc(
    class C {
     public:
      int x;
      int foo() { return x; }
    };
  )cc";
  auto StmtMatch =
      matchStmt(Snippet, returnStmt(hasReturnValue(ignoringImplicit(memberExpr(
                             hasObjectExpression(expr().bind("obj")))))));
  ASSERT_TRUE(StmtMatch);
  const Stencil Stencil = access("obj", "field");
  EXPECT_THAT_EXPECTED(Stencil->eval(StmtMatch->Result), HasValue("field"));
}

TEST_F(StencilTest, RunOp) {
  StringRef Id = "id";
  auto SimpleFn = [Id](const MatchResult &R) {
    return std::string(R.Nodes.getNodeAs<Stmt>(Id) != nullptr ? "Bound"
                                                              : "Unbound");
  };
  testExpr(Id, "3;", run(SimpleFn), "Bound");
}

TEST(StencilToStringTest, RawTextOp) {
  auto S = cat("foo bar baz");
  StringRef Expected = R"("foo bar baz")";
  EXPECT_EQ(S->toString(), Expected);
}

TEST(StencilToStringTest, RawTextOpEscaping) {
  auto S = cat("foo \"bar\" baz\\n");
  StringRef Expected = R"("foo \"bar\" baz\\n")";
  EXPECT_EQ(S->toString(), Expected);
}

TEST(StencilToStringTest, DebugPrintNodeOp) {
  auto S = dPrint("Id");
  StringRef Expected = R"repr(dPrint("Id"))repr";
  EXPECT_EQ(S->toString(), Expected);
}

TEST(StencilToStringTest, ExpressionOp) {
  auto S = expression("Id");
  StringRef Expected = R"repr(expression("Id"))repr";
  EXPECT_EQ(S->toString(), Expected);
}

TEST(StencilToStringTest, DerefOp) {
  auto S = deref("Id");
  StringRef Expected = R"repr(deref("Id"))repr";
  EXPECT_EQ(S->toString(), Expected);
}

TEST(StencilToStringTest, AddressOfOp) {
  auto S = addressOf("Id");
  StringRef Expected = R"repr(addressOf("Id"))repr";
  EXPECT_EQ(S->toString(), Expected);
}

TEST(StencilToStringTest, SelectionOp) {
  auto S1 = cat(node("node1"));
  EXPECT_EQ(S1->toString(), "selection(...)");
}

TEST(StencilToStringTest, AccessOpText) {
  auto S = access("Id", "memberData");
  StringRef Expected = R"repr(access("Id", "memberData"))repr";
  EXPECT_EQ(S->toString(), Expected);
}

TEST(StencilToStringTest, AccessOpSelector) {
  auto S = access("Id", selection(name("otherId")));
  StringRef Expected = R"repr(access("Id", selection(...)))repr";
  EXPECT_EQ(S->toString(), Expected);
}

TEST(StencilToStringTest, AccessOpStencil) {
  auto S = access("Id", cat("foo_", "bar"));
  StringRef Expected = R"repr(access("Id", seq("foo_", "bar")))repr";
  EXPECT_EQ(S->toString(), Expected);
}

TEST(StencilToStringTest, IfBoundOp) {
  auto S = ifBound("Id", text("trueText"), access("exprId", "memberData"));
  StringRef Expected =
      R"repr(ifBound("Id", "trueText", access("exprId", "memberData")))repr";
  EXPECT_EQ(S->toString(), Expected);
}

TEST(StencilToStringTest, RunOp) {
  auto F1 = [](const MatchResult &R) { return "foo"; };
  auto S1 = run(F1);
  EXPECT_EQ(S1->toString(), "run(...)");
}

TEST(StencilToStringTest, Sequence) {
  auto S = cat("foo", access("x", "m()"), "bar",
               ifBound("x", text("t"), access("e", "f")));
  StringRef Expected = R"repr(seq("foo", access("x", "m()"), "bar", )repr"
                       R"repr(ifBound("x", "t", access("e", "f"))))repr";
  EXPECT_EQ(S->toString(), Expected);
}

TEST(StencilToStringTest, SequenceEmpty) {
  auto S = cat();
  StringRef Expected = "seq()";
  EXPECT_EQ(S->toString(), Expected);
}

TEST(StencilToStringTest, SequenceSingle) {
  auto S = cat("foo");
  StringRef Expected = "\"foo\"";
  EXPECT_EQ(S->toString(), Expected);
}

TEST(StencilToStringTest, SequenceFromVector) {
  auto S = catVector({text("foo"), access("x", "m()"), text("bar"),
                      ifBound("x", text("t"), access("e", "f"))});
  StringRef Expected = R"repr(seq("foo", access("x", "m()"), "bar", )repr"
                       R"repr(ifBound("x", "t", access("e", "f"))))repr";
  EXPECT_EQ(S->toString(), Expected);
}
} // namespace