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