clang-tools  3.9.0
ProBoundsConstantArrayIndexCheck.cpp
Go to the documentation of this file.
1 //===--- ProBoundsConstantArrayIndexCheck.cpp - clang-tidy-----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/Frontend/CompilerInstance.h"
14 #include "clang/Lex/Preprocessor.h"
15 
16 using namespace clang::ast_matchers;
17 
18 namespace clang {
19 namespace tidy {
20 namespace cppcoreguidelines {
21 
22 ProBoundsConstantArrayIndexCheck::ProBoundsConstantArrayIndexCheck(
23  StringRef Name, ClangTidyContext *Context)
24  : ClangTidyCheck(Name, Context), GslHeader(Options.get("GslHeader", "")),
25  IncludeStyle(utils::IncludeSorter::parseIncludeStyle(
26  Options.get("IncludeStyle", "llvm"))) {}
27 
30  Options.store(Opts, "GslHeader", GslHeader);
31  Options.store(Opts, "IncludeStyle", IncludeStyle);
32 }
33 
35  CompilerInstance &Compiler) {
36  if (!getLangOpts().CPlusPlus)
37  return;
38 
39  Inserter.reset(new utils::IncludeInserter(
40  Compiler.getSourceManager(), Compiler.getLangOpts(), IncludeStyle));
41  Compiler.getPreprocessor().addPPCallbacks(Inserter->CreatePPCallbacks());
42 }
43 
45  if (!getLangOpts().CPlusPlus)
46  return;
47 
48  Finder->addMatcher(arraySubscriptExpr(hasBase(ignoringImpCasts(hasType(
49  constantArrayType().bind("type")))),
50  hasIndex(expr().bind("index")))
51  .bind("expr"),
52  this);
53 
54  Finder->addMatcher(
55  cxxOperatorCallExpr(
56  hasOverloadedOperatorName("[]"),
57  hasArgument(
58  0, hasType(cxxRecordDecl(hasName("::std::array")).bind("type"))),
59  hasArgument(1, expr().bind("index")))
60  .bind("expr"),
61  this);
62 }
63 
65  const MatchFinder::MatchResult &Result) {
66  const auto *Matched = Result.Nodes.getNodeAs<Expr>("expr");
67  const auto *IndexExpr = Result.Nodes.getNodeAs<Expr>("index");
68 
69  if (IndexExpr->isValueDependent())
70  return; // We check in the specialization.
71 
72  llvm::APSInt Index;
73  if (!IndexExpr->isIntegerConstantExpr(Index, *Result.Context, nullptr,
74  /*isEvaluated=*/true)) {
75  SourceRange BaseRange;
76  if (const auto *ArraySubscriptE = dyn_cast<ArraySubscriptExpr>(Matched))
77  BaseRange = ArraySubscriptE->getBase()->getSourceRange();
78  else
79  BaseRange =
80  dyn_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; use gsl::at() "
86  "instead");
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->getLocEnd(), ")");
94 
95  Optional<FixItHint> Insertion = Inserter->CreateIncludeInsertion(
96  Result.SourceManager->getMainFileID(), GslHeader,
97  /*IsAngled=*/false);
98  if (Insertion)
99  Diag << Insertion.getValue();
100  }
101  return;
102  }
103 
104  const auto *StdArrayDecl =
105  Result.Nodes.getNodeAs<ClassTemplateSpecializationDecl>("type");
106 
107  // For static arrays, this is handled in clang-diagnostic-array-bounds.
108  if (!StdArrayDecl)
109  return;
110 
111  if (Index.isSigned() && Index.isNegative()) {
112  diag(Matched->getExprLoc(),
113  "std::array<> index %0 is negative")
114  << Index.toString(10);
115  return;
116  }
117 
118  const TemplateArgumentList &TemplateArgs = StdArrayDecl->getTemplateArgs();
119  if (TemplateArgs.size() < 2)
120  return;
121  // First template arg of std::array is the type, second arg is the size.
122  const auto &SizeArg = TemplateArgs[1];
123  if (SizeArg.getKind() != TemplateArgument::Integral)
124  return;
125  llvm::APInt ArraySize = SizeArg.getAsIntegral();
126 
127  // Get uint64_t values, because different bitwidths would lead to an assertion
128  // in APInt::uge.
129  if (Index.getZExtValue() >= ArraySize.getZExtValue()) {
130  diag(Matched->getExprLoc(), "std::array<> index %0 is past the end of the array "
131  "(which contains %1 elements)")
132  << Index.toString(10) << ArraySize.toString(10, false);
133  }
134 }
135 
136 } // namespace cppcoreguidelines
137 } // namespace tidy
138 } // namespace clang
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
const std::string Name
Definition: USRFinder.cpp:140
LangOptions getLangOpts() const
Returns the language options from the context.
Definition: ClangTidy.h:170
std::unique_ptr< ast_matchers::MatchFinder > Finder
Definition: ClangTidy.cpp:210
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
Base class for all clang-tidy checks.
Definition: ClangTidy.h:110
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: ClangTidy.cpp:385
std::map< std::string, std::string > OptionMap
void registerPPCallbacks(CompilerInstance &Compiler) override
Override this to register PPCallbacks with Compiler.
Produces fixes to insert specified includes to source files, if not yet present.
ClangTidyContext & Context
Definition: ClangTidy.cpp:93
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.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
Definition: ClangTidy.cpp:352
const NamedDecl * Result
Definition: USRFinder.cpp:137