clang-tools  11.0.0
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  IncludeStyle(Options.getLocalOrGlobal("IncludeStyle",
25  utils::IncludeSorter::IS_LLVM)) {}
26 
29  Options.store(Opts, "GslHeader", GslHeader);
30  Options.store(Opts, "IncludeStyle", IncludeStyle);
31 }
32 
34  const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
35  Inserter = std::make_unique<utils::IncludeInserter>(SM, getLangOpts(),
36  IncludeStyle);
37  PP->addPPCallbacks(Inserter->CreatePPCallbacks());
38 }
39 
41  // Note: if a struct contains an array member, the compiler-generated
42  // constructor has an arraySubscriptExpr.
43  Finder->addMatcher(
44  arraySubscriptExpr(
45  hasBase(ignoringImpCasts(hasType(constantArrayType().bind("type")))),
46  hasIndex(expr().bind("index")), unless(hasAncestor(isImplicit())))
47  .bind("expr"),
48  this);
49 
50  Finder->addMatcher(
51  cxxOperatorCallExpr(
52  hasOverloadedOperatorName("[]"),
53  hasArgument(
54  0, hasType(cxxRecordDecl(hasName("::std::array")).bind("type"))),
55  hasArgument(1, expr().bind("index")))
56  .bind("expr"),
57  this);
58 }
59 
61  const MatchFinder::MatchResult &Result) {
62  const auto *Matched = Result.Nodes.getNodeAs<Expr>("expr");
63  const auto *IndexExpr = Result.Nodes.getNodeAs<Expr>("index");
64 
65  if (IndexExpr->isValueDependent())
66  return; // We check in the specialization.
67 
68  llvm::APSInt Index;
69  if (!IndexExpr->isIntegerConstantExpr(Index, *Result.Context, nullptr,
70  /*isEvaluated=*/true)) {
71  SourceRange BaseRange;
72  if (const auto *ArraySubscriptE = dyn_cast<ArraySubscriptExpr>(Matched))
73  BaseRange = ArraySubscriptE->getBase()->getSourceRange();
74  else
75  BaseRange =
76  dyn_cast<CXXOperatorCallExpr>(Matched)->getArg(0)->getSourceRange();
77  SourceRange IndexRange = IndexExpr->getSourceRange();
78 
79  auto Diag = diag(Matched->getExprLoc(),
80  "do not use array subscript when the index is "
81  "not an integer constant expression; use gsl::at() "
82  "instead");
83  if (!GslHeader.empty()) {
84  Diag << FixItHint::CreateInsertion(BaseRange.getBegin(), "gsl::at(")
85  << FixItHint::CreateReplacement(
86  SourceRange(BaseRange.getEnd().getLocWithOffset(1),
87  IndexRange.getBegin().getLocWithOffset(-1)),
88  ", ")
89  << FixItHint::CreateReplacement(Matched->getEndLoc(), ")")
90  << Inserter->CreateIncludeInsertion(
91  Result.SourceManager->getMainFileID(), GslHeader,
92  /*IsAngled=*/false);
93  }
94  return;
95  }
96 
97  const auto *StdArrayDecl =
98  Result.Nodes.getNodeAs<ClassTemplateSpecializationDecl>("type");
99 
100  // For static arrays, this is handled in clang-diagnostic-array-bounds.
101  if (!StdArrayDecl)
102  return;
103 
104  if (Index.isSigned() && Index.isNegative()) {
105  diag(Matched->getExprLoc(), "std::array<> index %0 is negative")
106  << Index.toString(10);
107  return;
108  }
109 
110  const TemplateArgumentList &TemplateArgs = StdArrayDecl->getTemplateArgs();
111  if (TemplateArgs.size() < 2)
112  return;
113  // First template arg of std::array is the type, second arg is the size.
114  const auto &SizeArg = TemplateArgs[1];
115  if (SizeArg.getKind() != TemplateArgument::Integral)
116  return;
117  llvm::APInt ArraySize = SizeArg.getAsIntegral();
118 
119  // Get uint64_t values, because different bitwidths would lead to an assertion
120  // in APInt::uge.
121  if (Index.getZExtValue() >= ArraySize.getZExtValue()) {
122  diag(Matched->getExprLoc(),
123  "std::array<> index %0 is past the end of the array "
124  "(which contains %1 elements)")
125  << Index.toString(10) << ArraySize.toString(10, false);
126  }
127 }
128 
129 } // namespace cppcoreguidelines
130 } // namespace tidy
131 } // namespace clang
clang::tidy::cppcoreguidelines::ProBoundsConstantArrayIndexCheck::registerMatchers
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
Definition: ProBoundsConstantArrayIndexCheck.cpp:40
clang::tidy::ClangTidyCheck
Base class for all clang-tidy checks.
Definition: ClangTidyCheck.h:114
clang::tidy::ClangTidyCheck::getLangOpts
const LangOptions & getLangOpts() const
Returns the language options from the context.
Definition: ClangTidyCheck.h:475
clang::ast_matchers
Definition: AbseilMatcher.h:14
clang::tidy::ClangTidyCheck::Options
OptionsView Options
Definition: ClangTidyCheck.h:471
clang::tidy::ClangTidyContext
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
Definition: ClangTidyDiagnosticConsumer.h:76
Name
static constexpr llvm::StringLiteral Name
Definition: UppercaseLiteralSuffixCheck.cpp:27
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:27
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:33
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:55
clang::tidy::bugprone::PP
static Preprocessor * PP
Definition: BadSignalToKillThreadCheck.cpp:29
Index
const SymbolIndex * Index
Definition: Dexp.cpp:95
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
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:60
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:152
ProBoundsConstantArrayIndexCheck.h
clang::tidy::ClangTidyOptions::OptionMap
std::map< std::string, ClangTidyValue > OptionMap
Definition: ClangTidyOptions.h:111