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 
10 #include "ProBoundsConstantArrayIndexCheck.h"
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 
27 void ProBoundsConstantArrayIndexCheck::storeOptions(
28     ClangTidyOptions::OptionMap &Opts) {
29   Options.store(Opts, "GslHeader", GslHeader);
30   Options.store(Opts, "IncludeStyle", IncludeStyle);
31 }
32 
33 void ProBoundsConstantArrayIndexCheck::registerPPCallbacks(
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 
43 void ProBoundsConstantArrayIndexCheck::registerMatchers(MatchFinder *Finder) {
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 
63 void ProBoundsConstantArrayIndexCheck::check(
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
133