1//===--- OptionalValueConversionCheck.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 "OptionalValueConversionCheck.h"
10#include "../utils/LexerUtils.h"
11#include "../utils/Matchers.h"
12#include "../utils/OptionsUtils.h"
13#include "clang/AST/ASTContext.h"
14#include "clang/ASTMatchers/ASTMatchFinder.h"
15
16using namespace clang::ast_matchers;
17
18namespace clang::tidy::bugprone {
19
20namespace {
21
22AST_MATCHER_P(QualType, hasCleanType, ast_matchers::internal::Matcher<QualType>,
23 InnerMatcher) {
24 return InnerMatcher.matches(
25 Node: Node.getNonReferenceType().getUnqualifiedType().getCanonicalType(),
26 Finder, Builder);
27}
28
29} // namespace
30
31OptionalValueConversionCheck::OptionalValueConversionCheck(
32 StringRef Name, ClangTidyContext *Context)
33 : ClangTidyCheck(Name, Context),
34 OptionalTypes(utils::options::parseStringList(
35 Option: Options.get(LocalName: "OptionalTypes",
36 Default: "::std::optional;::absl::optional;::boost::optional"))),
37 ValueMethods(utils::options::parseStringList(
38 Option: Options.get(LocalName: "ValueMethods", Default: "::value$;::get$"))) {}
39
40std::optional<TraversalKind>
41OptionalValueConversionCheck::getCheckTraversalKind() const {
42 return TK_AsIs;
43}
44
45void OptionalValueConversionCheck::registerMatchers(MatchFinder *Finder) {
46 auto ConstructTypeMatcher =
47 qualType(hasCleanType(InnerMatcher: qualType().bind(ID: "optional-type")));
48
49 auto CallTypeMatcher =
50 qualType(hasCleanType(InnerMatcher: equalsBoundNode(ID: "optional-type")));
51
52 auto OptionalDereferenceMatcher = callExpr(
53 anyOf(
54 cxxOperatorCallExpr(hasOverloadedOperatorName(Name: "*"),
55 hasUnaryOperand(InnerMatcher: hasType(InnerMatcher: CallTypeMatcher)))
56 .bind(ID: "op-call"),
57 cxxMemberCallExpr(thisPointerType(InnerMatcher: CallTypeMatcher),
58 callee(InnerMatcher: cxxMethodDecl(anyOf(
59 hasOverloadedOperatorName(Name: "*"),
60 matchers::matchesAnyListedName(NameList: ValueMethods)))))
61 .bind(ID: "member-call")),
62 hasType(InnerMatcher: qualType().bind(ID: "value-type")));
63
64 auto StdMoveCallMatcher =
65 callExpr(argumentCountIs(N: 1), callee(InnerMatcher: functionDecl(hasName(Name: "::std::move"))),
66 hasArgument(N: 0, InnerMatcher: ignoringImpCasts(InnerMatcher: OptionalDereferenceMatcher)));
67 Finder->addMatcher(
68 NodeMatch: cxxConstructExpr(
69 argumentCountIs(N: 1U),
70 hasDeclaration(InnerMatcher: cxxConstructorDecl(
71 ofClass(InnerMatcher: matchers::matchesAnyListedName(NameList: OptionalTypes)))),
72 hasType(InnerMatcher: ConstructTypeMatcher),
73 hasArgument(N: 0U, InnerMatcher: ignoringImpCasts(InnerMatcher: anyOf(OptionalDereferenceMatcher,
74 StdMoveCallMatcher))))
75 .bind(ID: "expr"),
76 Action: this);
77}
78
79void OptionalValueConversionCheck::storeOptions(
80 ClangTidyOptions::OptionMap &Opts) {
81 Options.store(Options&: Opts, LocalName: "OptionalTypes",
82 Value: utils::options::serializeStringList(Strings: OptionalTypes));
83 Options.store(Options&: Opts, LocalName: "ValueMethods",
84 Value: utils::options::serializeStringList(Strings: ValueMethods));
85}
86
87void OptionalValueConversionCheck::check(
88 const MatchFinder::MatchResult &Result) {
89 const auto *MatchedExpr = Result.Nodes.getNodeAs<Expr>(ID: "expr");
90 const auto *OptionalType = Result.Nodes.getNodeAs<QualType>(ID: "optional-type");
91 const auto *ValueType = Result.Nodes.getNodeAs<QualType>(ID: "value-type");
92
93 diag(Loc: MatchedExpr->getExprLoc(),
94 Description: "conversion from %0 into %1 and back into %0, remove potentially "
95 "error-prone optional dereference")
96 << *OptionalType << ValueType->getUnqualifiedType();
97
98 if (const auto *OperatorExpr =
99 Result.Nodes.getNodeAs<CXXOperatorCallExpr>(ID: "op-call")) {
100 diag(Loc: OperatorExpr->getExprLoc(), Description: "remove '*' to silence this warning",
101 Level: DiagnosticIDs::Note)
102 << FixItHint::CreateRemoval(RemoveRange: CharSourceRange::getTokenRange(
103 B: OperatorExpr->getBeginLoc(), E: OperatorExpr->getExprLoc()));
104 return;
105 }
106 if (const auto *CallExpr =
107 Result.Nodes.getNodeAs<CXXMemberCallExpr>(ID: "member-call")) {
108 const SourceLocation Begin =
109 utils::lexer::getPreviousToken(Location: CallExpr->getExprLoc(),
110 SM: *Result.SourceManager, LangOpts: getLangOpts())
111 .getLocation();
112 auto Diag =
113 diag(Loc: CallExpr->getExprLoc(),
114 Description: "remove call to %0 to silence this warning", Level: DiagnosticIDs::Note);
115 Diag << CallExpr->getMethodDecl()
116 << FixItHint::CreateRemoval(
117 CharSourceRange::getTokenRange(Begin, CallExpr->getEndLoc()));
118 if (const auto *Member =
119 llvm::dyn_cast<MemberExpr>(CallExpr->getCallee()->IgnoreImplicit());
120 Member && Member->isArrow())
121 Diag << FixItHint::CreateInsertion(InsertionLoc: CallExpr->getBeginLoc(), Code: "*");
122 return;
123 }
124}
125
126} // namespace clang::tidy::bugprone
127

source code of clang-tools-extra/clang-tidy/bugprone/OptionalValueConversionCheck.cpp