clang-tools  3.8.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 
21 ProBoundsConstantArrayIndexCheck::ProBoundsConstantArrayIndexCheck(
22  StringRef Name, ClangTidyContext *Context)
23  : ClangTidyCheck(Name, Context), GslHeader(Options.get("GslHeader", "")),
24  IncludeStyle(IncludeSorter::parseIncludeStyle(
25  Options.get("IncludeStyle", "llvm"))) {}
26 
29  Options.store(Opts, "GslHeader", GslHeader);
30  Options.store(Opts, "IncludeStyle", IncludeStyle);
31 }
32 
34  CompilerInstance &Compiler) {
35  if (!getLangOpts().CPlusPlus)
36  return;
37 
38  Inserter.reset(new IncludeInserter(Compiler.getSourceManager(),
39  Compiler.getLangOpts(), IncludeStyle));
40  Compiler.getPreprocessor().addPPCallbacks(Inserter->CreatePPCallbacks());
41 }
42 
44  if (!getLangOpts().CPlusPlus)
45  return;
46 
47  Finder->addMatcher(arraySubscriptExpr(hasBase(ignoringImpCasts(hasType(
48  constantArrayType().bind("type")))),
49  hasIndex(expr().bind("index")))
50  .bind("expr"),
51  this);
52 
53  Finder->addMatcher(
54  cxxOperatorCallExpr(
55  hasOverloadedOperatorName("[]"),
56  hasArgument(
57  0, hasType(cxxRecordDecl(hasName("::std::array")).bind("type"))),
58  hasArgument(1, expr().bind("index")))
59  .bind("expr"),
60  this);
61 }
62 
64  const MatchFinder::MatchResult &Result) {
65  const auto *Matched = Result.Nodes.getNodeAs<Expr>("expr");
66  const auto *IndexExpr = Result.Nodes.getNodeAs<Expr>("index");
67  llvm::APSInt Index;
68  if (!IndexExpr->isIntegerConstantExpr(Index, *Result.Context, nullptr,
69  /*isEvaluated=*/true)) {
70  SourceRange BaseRange;
71  if (const auto *ArraySubscriptE = dyn_cast<ArraySubscriptExpr>(Matched))
72  BaseRange = ArraySubscriptE->getBase()->getSourceRange();
73  else
74  BaseRange =
75  dyn_cast<CXXOperatorCallExpr>(Matched)->getArg(0)->getSourceRange();
76  SourceRange IndexRange = IndexExpr->getSourceRange();
77 
78  auto Diag = diag(Matched->getExprLoc(),
79  "do not use array subscript when the index is "
80  "not an integer constant expression; use gsl::at() "
81  "instead");
82  if (!GslHeader.empty()) {
83  Diag << FixItHint::CreateInsertion(BaseRange.getBegin(), "gsl::at(")
84  << FixItHint::CreateReplacement(
85  SourceRange(BaseRange.getEnd().getLocWithOffset(1),
86  IndexRange.getBegin().getLocWithOffset(-1)),
87  ", ")
88  << FixItHint::CreateReplacement(Matched->getLocEnd(), ")");
89 
90  Optional<FixItHint> Insertion = Inserter->CreateIncludeInsertion(
91  Result.SourceManager->getMainFileID(), GslHeader,
92  /*IsAngled=*/false);
93  if (Insertion)
94  Diag << Insertion.getValue();
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(),
108  "std::array<> index %0 is negative")
109  << Index.toString(10);
110  return;
111  }
112 
113  const TemplateArgumentList &TemplateArgs = StdArrayDecl->getTemplateArgs();
114  if (TemplateArgs.size() < 2)
115  return;
116  // First template arg of std::array is the type, second arg is the size.
117  const auto &SizeArg = TemplateArgs[1];
118  if (SizeArg.getKind() != TemplateArgument::Integral)
119  return;
120  llvm::APInt ArraySize = SizeArg.getAsIntegral();
121 
122  // Get uint64_t values, because different bitwidths would lead to an assertion
123  // in APInt::uge.
124  if (Index.getZExtValue() >= ArraySize.getZExtValue()) {
125  diag(Matched->getExprLoc(), "std::array<> index %0 is past the end of the array "
126  "(which contains %1 elements)")
127  << Index.toString(10) << ArraySize.toString(10, false);
128  }
129 }
130 
131 } // namespace tidy
132 } // namespace clang
LangOptions getLangOpts() const
Returns the language options from the context.
Definition: ClangTidy.h:162
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register ASTMatchers 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...
StringHandle Name
std::unique_ptr< ast_matchers::MatchFinder > Finder
Definition: ClangTidy.cpp:188
Base class for all clang-tidy checks.
Definition: ClangTidy.h:102
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:344
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
std::map< std::string, std::string > OptionMap
ClangTidyContext & Context
Definition: ClangTidy.cpp:93
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void registerPPCallbacks(CompilerInstance &Compiler) override
Override this to register PPCallbacks with Compiler.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
Definition: ClangTidy.cpp:323
const NamedDecl * Result
Definition: USRFinder.cpp:121