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