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