10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/Frontend/CompilerInstance.h"
13 #include "clang/Lex/Preprocessor.h"
19 namespace cppcoreguidelines {
21 ProBoundsConstantArrayIndexCheck::ProBoundsConstantArrayIndexCheck(
24 Inserter(Options.getLocalOrGlobal(
"IncludeStyle",
25 utils::IncludeSorter::IS_LLVM),
26 areDiagsSelfContained()) {}
35 const SourceManager &SM, Preprocessor *
PP, Preprocessor *ModuleExpanderPP) {
42 Finder->addMatcher(arraySubscriptExpr(hasBase(ignoringImpCasts(hasType(
43 constantArrayType().bind(
"type")))),
44 hasIndex(expr().bind(
"index")),
45 unless(hasAncestor(decl(isImplicit()))))
51 hasOverloadedOperatorName(
"[]"),
53 0, hasType(cxxRecordDecl(hasName(
"::std::array")).bind(
"type"))),
54 hasArgument(1, expr().bind(
"index")))
60 const MatchFinder::MatchResult &Result) {
61 const auto *Matched = Result.Nodes.getNodeAs<Expr>(
"expr");
62 const auto *IndexExpr = Result.Nodes.getNodeAs<Expr>(
"index");
64 if (IndexExpr->isValueDependent())
67 Optional<llvm::APSInt>
Index =
68 IndexExpr->getIntegerConstantExpr(*Result.Context);
70 SourceRange BaseRange;
71 if (
const auto *ArraySubscriptE = dyn_cast<ArraySubscriptExpr>(Matched))
72 BaseRange = ArraySubscriptE->getBase()->getSourceRange();
75 cast<CXXOperatorCallExpr>(Matched)->getArg(0)->getSourceRange();
76 SourceRange IndexRange = IndexExpr->getSourceRange();
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)),
87 << FixItHint::CreateReplacement(Matched->getEndLoc(),
")")
93 const auto *StdArrayDecl =
94 Result.Nodes.getNodeAs<ClassTemplateSpecializationDecl>(
"type");
100 if (
Index->isSigned() &&
Index->isNegative()) {
101 diag(Matched->getExprLoc(),
"std::array<> index %0 is negative")
106 const TemplateArgumentList &TemplateArgs = StdArrayDecl->getTemplateArgs();
107 if (TemplateArgs.size() < 2)
110 const auto &SizeArg = TemplateArgs[1];
111 if (SizeArg.getKind() != TemplateArgument::Integral)
113 llvm::APInt ArraySize = SizeArg.getAsIntegral();
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)")