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

source code of clang-tools-extra/clang-tidy/bugprone/SizeofContainerCheck.cpp