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 Inserter(Options.getLocalOrGlobal("IncludeStyle", 25 utils::IncludeSorter::IS_LLVM)) {} 26 27 void ProBoundsConstantArrayIndexCheck::storeOptions( 28 ClangTidyOptions::OptionMap &Opts) { 29 Options.store(Opts, "GslHeader", GslHeader); 30 Options.store(Opts, "IncludeStyle", Inserter.getStyle()); 31 } 32 33 void ProBoundsConstantArrayIndexCheck::registerPPCallbacks( 34 const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) { 35 Inserter.registerPreprocessor(PP); 36 } 37 38 void ProBoundsConstantArrayIndexCheck::registerMatchers(MatchFinder *Finder) { 39 // Note: if a struct contains an array member, the compiler-generated 40 // constructor has an arraySubscriptExpr. 41 Finder->addMatcher( 42 arraySubscriptExpr( 43 hasBase(ignoringImpCasts(hasType(constantArrayType().bind("type")))), 44 hasIndex(expr().bind("index")), unless(hasAncestor(isImplicit()))) 45 .bind("expr"), 46 this); 47 48 Finder->addMatcher( 49 cxxOperatorCallExpr( 50 hasOverloadedOperatorName("[]"), 51 hasArgument( 52 0, hasType(cxxRecordDecl(hasName("::std::array")).bind("type"))), 53 hasArgument(1, expr().bind("index"))) 54 .bind("expr"), 55 this); 56 } 57 58 void ProBoundsConstantArrayIndexCheck::check( 59 const MatchFinder::MatchResult &Result) { 60 const auto *Matched = Result.Nodes.getNodeAs<Expr>("expr"); 61 const auto *IndexExpr = Result.Nodes.getNodeAs<Expr>("index"); 62 63 if (IndexExpr->isValueDependent()) 64 return; // We check in the specialization. 65 66 Optional<llvm::APSInt> Index = 67 IndexExpr->getIntegerConstantExpr(*Result.Context); 68 if (!Index) { 69 SourceRange BaseRange; 70 if (const auto *ArraySubscriptE = dyn_cast<ArraySubscriptExpr>(Matched)) 71 BaseRange = ArraySubscriptE->getBase()->getSourceRange(); 72 else 73 BaseRange = 74 dyn_cast<CXXOperatorCallExpr>(Matched)->getArg(0)->getSourceRange(); 75 SourceRange IndexRange = IndexExpr->getSourceRange(); 76 77 auto Diag = diag(Matched->getExprLoc(), 78 "do not use array subscript when the index is " 79 "not an integer constant expression; use gsl::at() " 80 "instead"); 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