1 //===--- ProBoundsConstantArrayIndexCheck.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 "ProBoundsConstantArrayIndexCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/Frontend/CompilerInstance.h"
13 #include "clang/Lex/Preprocessor.h"
16 using namespace clang::ast_matchers
;
18 namespace clang::tidy::cppcoreguidelines
{
20 ProBoundsConstantArrayIndexCheck::ProBoundsConstantArrayIndexCheck(
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()) {}
27 void ProBoundsConstantArrayIndexCheck::storeOptions(
28 ClangTidyOptions::OptionMap
&Opts
) {
29 Options
.store(Opts
, "GslHeader", GslHeader
);
30 Options
.store(Opts
, "IncludeStyle", Inserter
.getStyle());
33 void ProBoundsConstantArrayIndexCheck::registerPPCallbacks(
34 const SourceManager
&SM
, Preprocessor
*PP
, Preprocessor
*ModuleExpanderPP
) {
35 Inserter
.registerPreprocessor(PP
);
38 void ProBoundsConstantArrayIndexCheck::registerMatchers(MatchFinder
*Finder
) {
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()))))
50 hasOverloadedOperatorName("[]"),
52 ofClass(cxxRecordDecl(hasName("::std::array")).bind("type")))),
53 hasArgument(1, expr().bind("index")))
58 void ProBoundsConstantArrayIndexCheck::check(
59 const MatchFinder::MatchResult
&Result
) {
60 const auto *Matched
= Result
.Nodes
.getNodeAs
<Expr
>("expr");
61 const auto *IndexExpr
= Result
.Nodes
.getNodeAs
<Expr
>("index");
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
))
69 if (IndexExpr
->isValueDependent())
70 return; // We check in the specialization.
72 std::optional
<llvm::APSInt
> Index
=
73 IndexExpr
->getIntegerConstantExpr(*Result
.Context
);
75 SourceRange BaseRange
;
76 if (const auto *ArraySubscriptE
= dyn_cast
<ArraySubscriptExpr
>(Matched
))
77 BaseRange
= ArraySubscriptE
->getBase()->getSourceRange();
80 cast
<CXXOperatorCallExpr
>(Matched
)->getArg(0)->getSourceRange();
81 SourceRange IndexRange
= IndexExpr
->getSourceRange();
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)),
92 << FixItHint::CreateReplacement(Matched
->getEndLoc(), ")")
93 << Inserter
.createMainFileIncludeInsertion(GslHeader
);
98 const auto *StdArrayDecl
=
99 Result
.Nodes
.getNodeAs
<ClassTemplateSpecializationDecl
>("type");
101 // For static arrays, this is handled in clang-diagnostic-array-bounds.
105 if (Index
->isSigned() && Index
->isNegative()) {
106 diag(Matched
->getExprLoc(), "std::array<> index %0 is negative")
107 << toString(*Index
, 10);
111 const TemplateArgumentList
&TemplateArgs
= StdArrayDecl
->getTemplateArgs();
112 if (TemplateArgs
.size() < 2)
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
)
118 llvm::APInt ArraySize
= SizeArg
.getAsIntegral();
120 // Get uint64_t values, because different bitwidths would lead to an assertion
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);
130 } // namespace clang::tidy::cppcoreguidelines