File: OptionalValueConversionCheck.cpp

package info (click to toggle)
llvm-toolchain-20 1%3A20.1.8-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 2,111,696 kB
  • sloc: cpp: 7,438,781; ansic: 1,393,871; asm: 1,012,926; python: 241,771; f90: 86,635; objc: 75,411; lisp: 42,144; pascal: 17,286; sh: 8,596; ml: 5,082; perl: 4,730; makefile: 3,591; awk: 3,523; javascript: 2,251; xml: 892; fortran: 672
file content (147 lines) | stat: -rw-r--r-- 5,834 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
//===--- OptionalValueConversionCheck.cpp - clang-tidy --------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "OptionalValueConversionCheck.h"
#include "../utils/LexerUtils.h"
#include "../utils/Matchers.h"
#include "../utils/OptionsUtils.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include <array>

using namespace clang::ast_matchers;
using clang::ast_matchers::internal::Matcher;

namespace clang::tidy::bugprone {

namespace {

AST_MATCHER_P(QualType, hasCleanType, Matcher<QualType>, InnerMatcher) {
  return InnerMatcher.matches(
      Node.getNonReferenceType().getUnqualifiedType().getCanonicalType(),
      Finder, Builder);
}

constexpr std::array<StringRef, 2> NameList{
    "::std::make_unique",
    "::std::make_shared",
};

Matcher<Expr> constructFrom(Matcher<QualType> TypeMatcher,
                            Matcher<Expr> ArgumentMatcher) {
  return expr(
      anyOf(
          // construct optional
          cxxConstructExpr(argumentCountIs(1U), hasType(TypeMatcher),
                           hasArgument(0U, ArgumentMatcher)),
          // known template methods in std
          callExpr(argumentCountIs(1),
                   callee(functionDecl(
                       matchers::matchesAnyListedName(NameList),
                       hasTemplateArgument(0, refersToType(TypeMatcher)))),
                   hasArgument(0, ArgumentMatcher))),
      unless(anyOf(hasAncestor(typeLoc()),
                   hasAncestor(expr(matchers::hasUnevaluatedContext())))));
}

} // namespace

OptionalValueConversionCheck::OptionalValueConversionCheck(
    StringRef Name, ClangTidyContext *Context)
    : ClangTidyCheck(Name, Context),
      OptionalTypes(utils::options::parseStringList(
          Options.get("OptionalTypes",
                      "::std::optional;::absl::optional;::boost::optional"))),
      ValueMethods(utils::options::parseStringList(
          Options.get("ValueMethods", "::value$;::get$"))) {}

std::optional<TraversalKind>
OptionalValueConversionCheck::getCheckTraversalKind() const {
  return TK_AsIs;
}

void OptionalValueConversionCheck::registerMatchers(MatchFinder *Finder) {
  auto BindOptionalType = qualType(
      hasCleanType(qualType(hasDeclaration(namedDecl(
                                matchers::matchesAnyListedName(OptionalTypes))))
                       .bind("optional-type")));

  auto EqualsBoundOptionalType =
      qualType(hasCleanType(equalsBoundNode("optional-type")));

  auto OptionalDereferenceMatcher = callExpr(
      anyOf(
          cxxOperatorCallExpr(hasOverloadedOperatorName("*"),
                              hasUnaryOperand(hasType(EqualsBoundOptionalType)))
              .bind("op-call"),
          cxxMemberCallExpr(thisPointerType(EqualsBoundOptionalType),
                            callee(cxxMethodDecl(anyOf(
                                hasOverloadedOperatorName("*"),
                                matchers::matchesAnyListedName(ValueMethods)))))
              .bind("member-call")),
      hasType(qualType().bind("value-type")));

  auto StdMoveCallMatcher =
      callExpr(argumentCountIs(1), callee(functionDecl(hasName("::std::move"))),
               hasArgument(0, ignoringImpCasts(OptionalDereferenceMatcher)));
  Finder->addMatcher(
      expr(constructFrom(BindOptionalType,
                         ignoringImpCasts(anyOf(OptionalDereferenceMatcher,
                                                StdMoveCallMatcher))))
          .bind("expr"),
      this);
}

void OptionalValueConversionCheck::storeOptions(
    ClangTidyOptions::OptionMap &Opts) {
  Options.store(Opts, "OptionalTypes",
                utils::options::serializeStringList(OptionalTypes));
  Options.store(Opts, "ValueMethods",
                utils::options::serializeStringList(ValueMethods));
}

void OptionalValueConversionCheck::check(
    const MatchFinder::MatchResult &Result) {
  const auto *MatchedExpr = Result.Nodes.getNodeAs<Expr>("expr");
  const auto *OptionalType = Result.Nodes.getNodeAs<QualType>("optional-type");
  const auto *ValueType = Result.Nodes.getNodeAs<QualType>("value-type");

  diag(MatchedExpr->getExprLoc(),
       "conversion from %0 into %1 and back into %0, remove potentially "
       "error-prone optional dereference")
      << *OptionalType << ValueType->getUnqualifiedType();

  if (const auto *OperatorExpr =
          Result.Nodes.getNodeAs<CXXOperatorCallExpr>("op-call")) {
    diag(OperatorExpr->getExprLoc(), "remove '*' to silence this warning",
         DiagnosticIDs::Note)
        << FixItHint::CreateRemoval(CharSourceRange::getTokenRange(
               OperatorExpr->getBeginLoc(), OperatorExpr->getExprLoc()));
    return;
  }
  if (const auto *CallExpr =
          Result.Nodes.getNodeAs<CXXMemberCallExpr>("member-call")) {
    const SourceLocation Begin =
        utils::lexer::getPreviousToken(CallExpr->getExprLoc(),
                                       *Result.SourceManager, getLangOpts())
            .getLocation();
    auto Diag =
        diag(CallExpr->getExprLoc(),
             "remove call to %0 to silence this warning", DiagnosticIDs::Note);
    Diag << CallExpr->getMethodDecl()
         << FixItHint::CreateRemoval(
                CharSourceRange::getTokenRange(Begin, CallExpr->getEndLoc()));
    if (const auto *Member =
            llvm::dyn_cast<MemberExpr>(CallExpr->getCallee()->IgnoreImplicit());
        Member && Member->isArrow())
      Diag << FixItHint::CreateInsertion(CallExpr->getBeginLoc(), "*");
    return;
  }
}

} // namespace clang::tidy::bugprone