clang-tools 20.0.0git
SizeofContainerCheck.cpp
Go to the documentation of this file.
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
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 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
35void 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
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.