SizeofContainerCheck.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. //===--- SizeofContainerCheck.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 "SizeofContainerCheck.h"
  9. #include "clang/AST/ASTContext.h"
  10. #include "clang/ASTMatchers/ASTMatchFinder.h"
  11. using namespace clang::ast_matchers;
  12. namespace clang::tidy::bugprone {
  13. void SizeofContainerCheck::registerMatchers(MatchFinder *Finder) {
  14. Finder->addMatcher(
  15. expr(unless(isInTemplateInstantiation()),
  16. expr(sizeOfExpr(has(ignoringParenImpCasts(
  17. expr(hasType(hasCanonicalType(hasDeclaration(cxxRecordDecl(
  18. matchesName("^(::std::|::string)"),
  19. unless(matchesName("^::std::(bitset|array)$")),
  20. hasMethod(cxxMethodDecl(hasName("size"), isPublic(),
  21. isConst())))))))))))
  22. .bind("sizeof"),
  23. // Ignore ARRAYSIZE(<array of containers>) pattern.
  24. unless(hasAncestor(binaryOperator(
  25. hasAnyOperatorName("/", "%"),
  26. hasLHS(ignoringParenCasts(sizeOfExpr(expr()))),
  27. hasRHS(ignoringParenCasts(equalsBoundNode("sizeof"))))))),
  28. this);
  29. }
  30. void SizeofContainerCheck::check(const MatchFinder::MatchResult &Result) {
  31. const auto *SizeOf =
  32. Result.Nodes.getNodeAs<UnaryExprOrTypeTraitExpr>("sizeof");
  33. auto Diag =
  34. diag(SizeOf->getBeginLoc(), "sizeof() doesn't return the size of the "
  35. "container; did you mean .size()?");
  36. }
  37. } // namespace clang::tidy::bugprone