clang-tools 19.0.0git
ProBoundsConstantArrayIndexCheck.cpp
Go to the documentation of this file.
1//===--- ProBoundsConstantArrayIndexCheck.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#include "clang/Frontend/CompilerInstance.h"
13#include "clang/Lex/Preprocessor.h"
14#include <optional>
15
16using namespace clang::ast_matchers;
17
19
21 StringRef Name, ClangTidyContext *Context)
22 : ClangTidyCheck(Name, Context), GslHeader(Options.get("GslHeader", "")),
23 Inserter(Options.getLocalOrGlobal("IncludeStyle",
24 utils::IncludeSorter::IS_LLVM),
25 areDiagsSelfContained()) {}
26
29 Options.store(Opts, "GslHeader", GslHeader);
30 Options.store(Opts, "IncludeStyle", Inserter.getStyle());
31}
32
34 const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
35 Inserter.registerPreprocessor(PP);
36}
37
39 // Note: if a struct contains an array member, the compiler-generated
40 // constructor has an arraySubscriptExpr.
41 Finder->addMatcher(arraySubscriptExpr(hasBase(ignoringImpCasts(hasType(
42 constantArrayType().bind("type")))),
43 hasIndex(expr().bind("index")),
44 unless(hasAncestor(decl(isImplicit()))))
45 .bind("expr"),
46 this);
47
48 Finder->addMatcher(
49 cxxOperatorCallExpr(
50 hasOverloadedOperatorName("[]"),
51 callee(cxxMethodDecl(
52 ofClass(cxxRecordDecl(hasName("::std::array")).bind("type")))),
53 hasArgument(1, expr().bind("index")))
54 .bind("expr"),
55 this);
56}
57
59 const MatchFinder::MatchResult &Result) {
60 const auto *Matched = Result.Nodes.getNodeAs<Expr>("expr");
61 const auto *IndexExpr = Result.Nodes.getNodeAs<Expr>("index");
62
63 // This expression can only appear inside ArrayInitLoopExpr, which
64 // is always implicitly generated. ArrayInitIndexExpr is not a
65 // constant, but we shouldn't report a warning for it.
66 if (isa<ArrayInitIndexExpr>(IndexExpr))
67 return;
68
69 if (IndexExpr->isValueDependent())
70 return; // We check in the specialization.
71
72 std::optional<llvm::APSInt> Index =
73 IndexExpr->getIntegerConstantExpr(*Result.Context);
74 if (!Index) {
75 SourceRange BaseRange;
76 if (const auto *ArraySubscriptE = dyn_cast<ArraySubscriptExpr>(Matched))
77 BaseRange = ArraySubscriptE->getBase()->getSourceRange();
78 else
79 BaseRange =
80 cast<CXXOperatorCallExpr>(Matched)->getArg(0)->getSourceRange();
81 SourceRange IndexRange = IndexExpr->getSourceRange();
82
83 auto Diag = diag(Matched->getExprLoc(),
84 "do not use array subscript when the index is "
85 "not an integer constant expression");
86 if (!GslHeader.empty()) {
87 Diag << FixItHint::CreateInsertion(BaseRange.getBegin(), "gsl::at(")
88 << FixItHint::CreateReplacement(
89 SourceRange(BaseRange.getEnd().getLocWithOffset(1),
90 IndexRange.getBegin().getLocWithOffset(-1)),
91 ", ")
92 << FixItHint::CreateReplacement(Matched->getEndLoc(), ")")
93 << Inserter.createMainFileIncludeInsertion(GslHeader);
94 }
95 return;
96 }
97
98 const auto *StdArrayDecl =
99 Result.Nodes.getNodeAs<ClassTemplateSpecializationDecl>("type");
100
101 // For static arrays, this is handled in clang-diagnostic-array-bounds.
102 if (!StdArrayDecl)
103 return;
104
105 if (Index->isSigned() && Index->isNegative()) {
106 diag(Matched->getExprLoc(), "std::array<> index %0 is negative")
107 << toString(*Index, 10);
108 return;
109 }
110
111 const TemplateArgumentList &TemplateArgs = StdArrayDecl->getTemplateArgs();
112 if (TemplateArgs.size() < 2)
113 return;
114 // First template arg of std::array is the type, second arg is the size.
115 const auto &SizeArg = TemplateArgs[1];
116 if (SizeArg.getKind() != TemplateArgument::Integral)
117 return;
118 llvm::APInt ArraySize = SizeArg.getAsIntegral();
119
120 // Get uint64_t values, because different bitwidths would lead to an assertion
121 // in APInt::uge.
122 if (Index->getZExtValue() >= ArraySize.getZExtValue()) {
123 diag(Matched->getExprLoc(),
124 "std::array<> index %0 is past the end of the array "
125 "(which contains %1 elements)")
126 << toString(*Index, 10) << toString(ArraySize, 10, false);
127 }
128}
129
130} // namespace clang::tidy::cppcoreguidelines
llvm::SmallString< 256U > Name
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Base class for all clang-tidy checks.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
Override this to register PPCallbacks in the preprocessor.
void registerPreprocessor(Preprocessor *PP)
Registers this with the Preprocessor PP, must be called before this class is used.
IncludeSorter::IncludeStyle getStyle() const
std::optional< FixItHint > createMainFileIncludeInsertion(llvm::StringRef Header)
Creates a Header inclusion directive fixit in the main file.
static llvm::StringRef toString(SpecialMemberFunctionsCheck::SpecialMemberFunctionKind K)
llvm::StringMap< ClangTidyValue > OptionMap