clang-tools 20.0.0git
OptionalValueConversionCheck.cpp
Go to the documentation of this file.
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
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.getNonReferenceType().getUnqualifiedType().getCanonicalType(),
26 Finder, Builder);
27}
28
29} // namespace
30
32 StringRef Name, ClangTidyContext *Context)
33 : ClangTidyCheck(Name, Context),
34 OptionalTypes(utils::options::parseStringList(
35 Options.get("OptionalTypes",
36 "::std::optional;::absl::optional;::boost::optional"))),
37 ValueMethods(utils::options::parseStringList(
38 Options.get("ValueMethods", "::value$;::get$"))) {}
39
40std::optional<TraversalKind>
42 return TK_AsIs;
43}
44
46 auto ConstructTypeMatcher =
47 qualType(hasCleanType(qualType().bind("optional-type")));
48
49 auto CallTypeMatcher =
50 qualType(hasCleanType(equalsBoundNode("optional-type")));
51
52 auto OptionalDereferenceMatcher = callExpr(
53 anyOf(
54 cxxOperatorCallExpr(hasOverloadedOperatorName("*"),
55 hasUnaryOperand(hasType(CallTypeMatcher)))
56 .bind("op-call"),
57 cxxMemberCallExpr(thisPointerType(CallTypeMatcher),
58 callee(cxxMethodDecl(anyOf(
59 hasOverloadedOperatorName("*"),
60 matchers::matchesAnyListedName(ValueMethods)))))
61 .bind("member-call")),
62 hasType(qualType().bind("value-type")));
63
64 auto StdMoveCallMatcher =
65 callExpr(argumentCountIs(1), callee(functionDecl(hasName("::std::move"))),
66 hasArgument(0, ignoringImpCasts(OptionalDereferenceMatcher)));
67 Finder->addMatcher(
68 cxxConstructExpr(
69 argumentCountIs(1U),
70 hasDeclaration(cxxConstructorDecl(
71 ofClass(matchers::matchesAnyListedName(OptionalTypes)))),
72 hasType(ConstructTypeMatcher),
73 hasArgument(0U, ignoringImpCasts(anyOf(OptionalDereferenceMatcher,
74 StdMoveCallMatcher))),
75 unless(anyOf(hasAncestor(typeLoc()),
76 hasAncestor(expr(matchers::hasUnevaluatedContext())))))
77 .bind("expr"),
78 this);
79}
80
83 Options.store(Opts, "OptionalTypes",
85 Options.store(Opts, "ValueMethods",
87}
88
90 const MatchFinder::MatchResult &Result) {
91 const auto *MatchedExpr = Result.Nodes.getNodeAs<Expr>("expr");
92 const auto *OptionalType = Result.Nodes.getNodeAs<QualType>("optional-type");
93 const auto *ValueType = Result.Nodes.getNodeAs<QualType>("value-type");
94
95 diag(MatchedExpr->getExprLoc(),
96 "conversion from %0 into %1 and back into %0, remove potentially "
97 "error-prone optional dereference")
98 << *OptionalType << ValueType->getUnqualifiedType();
99
100 if (const auto *OperatorExpr =
101 Result.Nodes.getNodeAs<CXXOperatorCallExpr>("op-call")) {
102 diag(OperatorExpr->getExprLoc(), "remove '*' to silence this warning",
103 DiagnosticIDs::Note)
104 << FixItHint::CreateRemoval(CharSourceRange::getTokenRange(
105 OperatorExpr->getBeginLoc(), OperatorExpr->getExprLoc()));
106 return;
107 }
108 if (const auto *CallExpr =
109 Result.Nodes.getNodeAs<CXXMemberCallExpr>("member-call")) {
110 const SourceLocation Begin =
111 utils::lexer::getPreviousToken(CallExpr->getExprLoc(),
112 *Result.SourceManager, getLangOpts())
113 .getLocation();
114 auto Diag =
115 diag(CallExpr->getExprLoc(),
116 "remove call to %0 to silence this warning", DiagnosticIDs::Note);
117 Diag << CallExpr->getMethodDecl()
118 << FixItHint::CreateRemoval(
119 CharSourceRange::getTokenRange(Begin, CallExpr->getEndLoc()));
120 if (const auto *Member =
121 llvm::dyn_cast<MemberExpr>(CallExpr->getCallee()->IgnoreImplicit());
122 Member && Member->isArrow())
123 Diag << FixItHint::CreateInsertion(CallExpr->getBeginLoc(), "*");
124 return;
125 }
126}
127
128} // namespace clang::tidy::bugprone
llvm::SmallString< 256U > Name
CodeCompletionBuilder Builder
::clang::DynTypedNode Node
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Base class for all clang-tidy checks.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
const LangOptions & getLangOpts() const
Returns the language options from the context.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
OptionalValueConversionCheck(StringRef Name, ClangTidyContext *Context)
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
std::optional< TraversalKind > getCheckTraversalKind() const override
AST_MATCHER_P(FunctionDecl, parameterCountGE, unsigned, N)
Matches functions that have at least the specified amount of parameters.
inline ::clang::ast_matchers::internal::Matcher< NamedDecl > matchesAnyListedName(llvm::ArrayRef< StringRef > NameList)
Token getPreviousToken(SourceLocation Location, const SourceManager &SM, const LangOptions &LangOpts, bool SkipComments)
Returns previous token or tok::unknown if not found.
Definition: LexerUtils.cpp:39
std::string serializeStringList(ArrayRef< StringRef > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
llvm::StringMap< ClangTidyValue > OptionMap