TemporaryObjectsCheck.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. //===--- TemporaryObjectsCheck.cpp - clang-tidy----------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "TemporaryObjectsCheck.h"
  9. #include "../utils/OptionsUtils.h"
  10. #include "clang/AST/ASTContext.h"
  11. #include "clang/ASTMatchers/ASTMatchFinder.h"
  12. #include "llvm/ADT/STLExtras.h"
  13. #include "llvm/ADT/SmallVector.h"
  14. #include <string>
  15. using namespace clang::ast_matchers;
  16. namespace clang::tidy::zircon {
  17. AST_MATCHER_P(CXXRecordDecl, matchesAnyName, ArrayRef<StringRef>, Names) {
  18. std::string QualifiedName = Node.getQualifiedNameAsString();
  19. return llvm::is_contained(Names, QualifiedName);
  20. }
  21. void TemporaryObjectsCheck::registerMatchers(MatchFinder *Finder) {
  22. // Matcher for default constructors.
  23. Finder->addMatcher(
  24. cxxTemporaryObjectExpr(hasDeclaration(cxxConstructorDecl(hasParent(
  25. cxxRecordDecl(matchesAnyName(Names))))))
  26. .bind("temps"),
  27. this);
  28. // Matcher for user-defined constructors.
  29. Finder->addMatcher(
  30. traverse(TK_AsIs,
  31. cxxConstructExpr(hasParent(cxxFunctionalCastExpr()),
  32. hasDeclaration(cxxConstructorDecl(hasParent(
  33. cxxRecordDecl(matchesAnyName(Names))))))
  34. .bind("temps")),
  35. this);
  36. }
  37. void TemporaryObjectsCheck::check(const MatchFinder::MatchResult &Result) {
  38. if (const auto *D = Result.Nodes.getNodeAs<CXXConstructExpr>("temps"))
  39. diag(D->getLocation(),
  40. "creating a temporary object of type %q0 is prohibited")
  41. << D->getConstructor()->getParent();
  42. }
  43. void TemporaryObjectsCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
  44. Options.store(Opts, "Names", utils::options::serializeStringList(Names));
  45. }
  46. } // namespace clang::tidy::zircon