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