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