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 
9 #include "ProBoundsConstantArrayIndexCheck.h"
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 #include <optional>
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       Inserter(Options.getLocalOrGlobal("IncludeStyle",
26                                         utils::IncludeSorter::IS_LLVM),
27                areDiagsSelfContained()) {}
28 
29 void ProBoundsConstantArrayIndexCheck::storeOptions(
30     ClangTidyOptions::OptionMap &Opts) {
31   Options.store(Opts, "GslHeader", GslHeader);
32   Options.store(Opts, "IncludeStyle", Inserter.getStyle());
33 }
34 
35 void ProBoundsConstantArrayIndexCheck::registerPPCallbacks(
36     const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
37   Inserter.registerPreprocessor(PP);
38 }
39 
40 void ProBoundsConstantArrayIndexCheck::registerMatchers(MatchFinder *Finder) {
41   // Note: if a struct contains an array member, the compiler-generated
42   // constructor has an arraySubscriptExpr.
43   Finder->addMatcher(arraySubscriptExpr(hasBase(ignoringImpCasts(hasType(
44                                             constantArrayType().bind("type")))),
45                                         hasIndex(expr().bind("index")),
46                                         unless(hasAncestor(decl(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 
60 void ProBoundsConstantArrayIndexCheck::check(
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   // This expression can only appear inside ArrayInitLoopExpr, which
66   // is always implicitly generated. ArrayInitIndexExpr is not a
67   // constant, but we shouldn't report a warning for it.
68   if (isa<ArrayInitIndexExpr>(IndexExpr))
69     return;
70 
71   if (IndexExpr->isValueDependent())
72     return; // We check in the specialization.
73 
74   Optional<llvm::APSInt> Index =
75       IndexExpr->getIntegerConstantExpr(*Result.Context);
76   if (!Index) {
77     SourceRange BaseRange;
78     if (const auto *ArraySubscriptE = dyn_cast<ArraySubscriptExpr>(Matched))
79       BaseRange = ArraySubscriptE->getBase()->getSourceRange();
80     else
81       BaseRange =
82           cast<CXXOperatorCallExpr>(Matched)->getArg(0)->getSourceRange();
83     SourceRange IndexRange = IndexExpr->getSourceRange();
84 
85     auto Diag = diag(Matched->getExprLoc(),
86                      "do not use array subscript when the index is "
87                      "not an integer constant expression");
88     if (!GslHeader.empty()) {
89       Diag << FixItHint::CreateInsertion(BaseRange.getBegin(), "gsl::at(")
90            << FixItHint::CreateReplacement(
91                   SourceRange(BaseRange.getEnd().getLocWithOffset(1),
92                               IndexRange.getBegin().getLocWithOffset(-1)),
93                   ", ")
94            << FixItHint::CreateReplacement(Matched->getEndLoc(), ")")
95            << Inserter.createMainFileIncludeInsertion(GslHeader);
96     }
97     return;
98   }
99 
100   const auto *StdArrayDecl =
101       Result.Nodes.getNodeAs<ClassTemplateSpecializationDecl>("type");
102 
103   // For static arrays, this is handled in clang-diagnostic-array-bounds.
104   if (!StdArrayDecl)
105     return;
106 
107   if (Index->isSigned() && Index->isNegative()) {
108     diag(Matched->getExprLoc(), "std::array<> index %0 is negative")
109         << toString(*Index, 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(),
126          "std::array<> index %0 is past the end of the array "
127          "(which contains %1 elements)")
128         << toString(*Index, 10) << toString(ArraySize, 10, false);
129   }
130 }
131 
132 } // namespace cppcoreguidelines
133 } // namespace tidy
134 } // namespace clang
135