1 //===--- SizeofContainerCheck.cpp - clang-tidy-----------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "SizeofContainerCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 using namespace clang::ast_matchers
;
15 namespace clang::tidy::bugprone
{
17 void SizeofContainerCheck::registerMatchers(MatchFinder
*Finder
) {
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(),
27 // Ignore ARRAYSIZE(<array of containers>) pattern.
28 unless(hasAncestor(binaryOperator(
29 hasAnyOperatorName("/", "%"),
30 hasLHS(ignoringParenCasts(sizeOfExpr(expr()))),
31 hasRHS(ignoringParenCasts(equalsBoundNode("sizeof"))))))),
35 void SizeofContainerCheck::check(const MatchFinder::MatchResult
&Result
) {
37 Result
.Nodes
.getNodeAs
<UnaryExprOrTypeTraitExpr
>("sizeof");
40 diag(SizeOf
->getBeginLoc(), "sizeof() doesn't return the size of the "
41 "container; did you mean .size()?");
44 } // namespace clang::tidy::bugprone