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

source code of clang-tools-extra/clang-tidy/readability/SimplifySubscriptExprCheck.cpp