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