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

Provided by KDAB

Privacy Policy
Update your C++ knowledge – Modern C++11/14/17 Training
Find out more

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