Debian Codegraph @

llvm-project/clang-tools-extra/clang-tidy/readability/SimplifySubscriptExprCheck.cpp

raw
1 //===--- SimplifySubscriptExprCheck.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 "SimplifySubscriptExprCheck.h"
10 #include "../utils/OptionsUtils.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13
14 using namespace clang::ast_matchers;
15
16 namespace clang::tidy::readability {
17
18 static const char KDefaultTypes[] =
19 "::std::basic_string;::std::basic_string_view;::std::vector;::std::array";
20
21 SimplifySubscriptExprCheck::SimplifySubscriptExprCheck(
22 StringRef Name, ClangTidyContext *Context)
23 : ClangTidyCheck(Name, Context), Types(utils::options::parseStringList(
24 Options.get("Types", KDefaultTypes))) {
25 }
26
27 void SimplifySubscriptExprCheck::registerMatchers(MatchFinder *Finder) {
28 const auto TypesMatcher = hasUnqualifiedDesugaredType(
29 recordType(hasDeclaration(cxxRecordDecl(hasAnyName(Types)))));
30
31 Finder->addMatcher(
32 arraySubscriptExpr(hasBase(
33 cxxMemberCallExpr(
34 has(memberExpr().bind("member")),
35 on(hasType(qualType(
36 unless(anyOf(substTemplateTypeParmType(),
37 hasDescendant(substTemplateTypeParmType()))),
38 anyOf(TypesMatcher, pointerType(pointee(TypesMatcher)))))),
39 callee(namedDecl(hasName("data"))))
40 .bind("call"))),
41 this);
42 }
43
44 void SimplifySubscriptExprCheck::check(const MatchFinder::MatchResult &Result) {
45 const auto *Call = Result.Nodes.getNodeAs<CXXMemberCallExpr>("call");
46 if (Result.Context->getSourceManager().isMacroBodyExpansion(
47 Call->getExprLoc()))
48 return;
49
50 const auto *Member = Result.Nodes.getNodeAs<MemberExpr>("member");
51 auto DiagBuilder =
52 diag(Member->getMemberLoc(),
53 "accessing an element of the container does not require a call to "
54 "'data()'; did you mean to use 'operator[]'?");
55 if (Member->isArrow())
56 DiagBuilder << FixItHint::CreateInsertion(Member->getBeginLoc(), "(*")
57 << FixItHint::CreateInsertion(Member->getOperatorLoc(), ")");
58 DiagBuilder << FixItHint::CreateRemoval(
59 {Member->getOperatorLoc(), Call->getEndLoc()});
60 }
61
62 void SimplifySubscriptExprCheck::storeOptions(
63 ClangTidyOptions::OptionMap &Opts) {
64 Options.store(Opts, "Types", utils::options::serializeStringList(Types));
65 }
66
67 } // namespace clang::tidy::readability