15#include "clang/AST/Decl.h"
16#include "clang/Basic/Diagnostic.h"
31static void recordFixes(
const VarDecl &Var, ASTContext &Context,
32 DiagnosticBuilder &Diagnostic) {
34 if (!Var.getType().isLocalConstQualified()) {
36 Var, Context, Qualifiers::Const))
44 const char *TextAfter = SM.getCharacterData(Loc, &Invalid);
47 const size_t Offset = std::strcspn(TextAfter,
"\n");
48 return Loc.getLocWithOffset(TextAfter[Offset] ==
'\0' ? Offset : Offset + 1);
52 DiagnosticBuilder &Diagnostic) {
53 auto &SM = Context.getSourceManager();
56 Context.getLangOpts());
57 std::optional<SourceLocation> PastNewLine =
59 if (Tok && PastNewLine) {
60 auto BeforeFirstTokenAfterComment = Tok->getLocation().getLocWithOffset(-1);
64 SM.isBeforeInTranslationUnit(*PastNewLine, BeforeFirstTokenAfterComment)
66 : BeforeFirstTokenAfterComment;
67 Diagnostic << FixItHint::CreateRemoval(
68 SourceRange(Stmt.getBeginLoc(), End));
70 Diagnostic << FixItHint::CreateRemoval(Stmt.getSourceRange());
76AST_MATCHER_FUNCTION_P(StatementMatcher,
77 isRefReturningMethodCallWithConstOverloads,
78 std::vector<StringRef>, ExcludedContainerTypes) {
84 const auto MethodDecl =
85 cxxMethodDecl(returns(hasCanonicalType(referenceType())))
87 const auto ReceiverExpr =
88 ignoringParenImpCasts(declRefExpr(to(varDecl().bind(
ObjectArgId))));
89 const auto OnExpr = anyOf(
93 unaryOperator(hasOperatorName(
"*"), hasUnaryOperand(ReceiverExpr)));
94 const auto ReceiverType =
95 hasCanonicalType(recordType(hasDeclaration(namedDecl(unless(
99 anyOf(cxxMemberCallExpr(callee(MethodDecl), on(OnExpr),
100 thisPointerType(ReceiverType)),
101 cxxOperatorCallExpr(callee(MethodDecl), hasArgument(0, OnExpr),
102 hasArgument(0, hasType(ReceiverType)))));
105AST_MATCHER(CXXMethodDecl, isStatic) {
return Node.isStatic(); }
107AST_MATCHER_FUNCTION(StatementMatcher, isConstRefReturningFunctionCall) {
112 return callExpr(argumentCountIs(0),
113 callee(functionDecl(returns(hasCanonicalType(
114 matchers::isReferenceToConst())),
115 unless(cxxMethodDecl(unless(isStatic()))))
121 std::vector<StringRef>, ExcludedContainerTypes) {
123 declRefExpr(to(varDecl(hasLocalStorage()).bind(
OldVarDeclId)));
125 anyOf(isConstRefReturningFunctionCall(),
126 isRefReturningMethodCallWithConstOverloads(ExcludedContainerTypes),
127 ignoringImpCasts(OldVarDeclRef),
128 ignoringImpCasts(unaryOperator(hasOperatorName(
"&"),
129 hasUnaryOperand(OldVarDeclRef)))));
147 const VarDecl &InitializingVar,
const Stmt &BlockStmt, ASTContext &Context,
148 const std::vector<StringRef> &ExcludedContainerTypes) {
149 const QualType T = InitializingVar.getType().getCanonicalType();
151 T->isPointerType() ? 1 : 0))
156 if (!isa<ReferenceType, PointerType>(T))
161 if (!InitializingVar.isLocalVarDecl() || !InitializingVar.hasInit())
165 match(initializerReturnsReferenceToConst(ExcludedContainerTypes),
166 *InitializingVar.getInit(), Context);
172 if (
const auto *OrigVar = selectFirst<VarDecl>(
ObjectArgId, Matches))
174 ExcludedContainerTypes);
176 if (
const auto *OrigVar = selectFirst<VarDecl>(
OldVarDeclId, Matches))
178 ExcludedContainerTypes);
184 ASTContext &Context) {
188static const SubstTemplateTypeParmType *
190 auto Matches = match(
191 qualType(anyOf(substTemplateTypeParmType().bind(
"subst"),
192 hasDescendant(substTemplateTypeParmType().bind(
"subst")))),
194 return selectFirst<SubstTemplateTypeParmType>(
"subst", Matches);
198 const QualType &InitializerType,
199 ASTContext &Context) {
200 if (
const SubstTemplateTypeParmType *VarTmplType =
202 if (
const SubstTemplateTypeParmType *InitializerTmplType =
204 const TemplateTypeParmDecl *VarTTP = VarTmplType->getReplacedParameter();
205 const TemplateTypeParmDecl *InitTTP =
206 InitializerTmplType->getReplacedParameter();
207 return (VarTTP->getDepth() != InitTTP->getDepth() ||
208 VarTTP->getIndex() != InitTTP->getIndex() ||
209 VarTTP->isParameterPack() != InitTTP->isParameterPack());
216 const BoundNodes &Nodes) {
218 return OldVar->getType();
221 const auto *MethodDecl = Nodes.getNodeAs<CXXMethodDecl>(
MethodDeclId);
222 return MethodDecl->getReturnType();
229 utils::options::parseStringList(Options.get(
"AllowedTypes",
""))),
230 ExcludedContainerTypes(
utils::options::parseStringList(
231 Options.get(
"ExcludedContainerTypes",
""))) {}
234 auto LocalVarCopiedFrom =
235 [
this](
const ast_matchers::internal::Matcher<Expr> &CopyCtorArg) {
239 unless(has(decompositionDecl())),
243 hasCanonicalType(allOf(
244 matchers::isExpensiveToCopy(),
245 unless(hasDeclaration(namedDecl(
246 hasName(
"::std::function")))))),
247 unless(hasDeclaration(namedDecl(
250 unless(isImplicit()),
251 hasInitializer(traverse(
254 hasDeclaration(cxxConstructorDecl(
255 isCopyConstructor())),
256 hasArgument(0, CopyCtorArg))
258 .bind(
"newVarDecl")))
264 LocalVarCopiedFrom(anyOf(
265 isConstRefReturningFunctionCall(),
266 isRefReturningMethodCallWithConstOverloads(ExcludedContainerTypes))),
269 Finder->addMatcher(LocalVarCopiedFrom(declRefExpr(
275 const MatchFinder::MatchResult &Result) {
276 const auto &NewVar = *Result.Nodes.getNodeAs<VarDecl>(
"newVarDecl");
277 const auto &BlockStmt = *Result.Nodes.getNodeAs<Stmt>(
"blockStmt");
278 const auto &VarDeclStmt = *Result.Nodes.getNodeAs<DeclStmt>(
"declStmt");
281 const bool IssueFix =
282 VarDeclStmt.isSingleDecl() && !NewVar.getLocation().isMacroID();
283 const bool IsVarUnused =
isVariableUnused(NewVar, BlockStmt, *Result.Context);
284 const bool IsVarOnlyUsedAsConst =
289 NewVar, BlockStmt, VarDeclStmt, *Result.Context,
290 IssueFix, IsVarUnused, IsVarOnlyUsedAsConst};
291 const auto *OldVar = Result.Nodes.getNodeAs<VarDecl>(
OldVarDeclId);
292 const auto *ObjectArg = Result.Nodes.getNodeAs<VarDecl>(
ObjectArgId);
293 const auto *CtorCall = Result.Nodes.getNodeAs<CXXConstructExpr>(
"ctorCall");
295 const TraversalKindScope RAII(*Result.Context, TK_AsIs);
300 for (
unsigned int I = 1; I < CtorCall->getNumArgs(); ++I)
301 if (!CtorCall->getArg(I)->isDefaultArgument())
314 if (OldVar ==
nullptr) {
316 handleCopyFromMethodReturn(Context, ObjectArg);
319 handleCopyFromLocalVar(Context, *OldVar);
323void UnnecessaryCopyInitializationCheck::handleCopyFromMethodReturn(
324 const CheckContext &Ctx,
const VarDecl *ObjectArg) {
325 const bool IsConstQualified = Ctx.Var.getType().isConstQualified();
326 if (!IsConstQualified && !Ctx.IsVarOnlyUsedAsConst)
328 if (ObjectArg !=
nullptr &&
330 ExcludedContainerTypes))
335void UnnecessaryCopyInitializationCheck::handleCopyFromLocalVar(
336 const CheckContext &Ctx,
const VarDecl &OldVar) {
337 if (!Ctx.IsVarOnlyUsedAsConst ||
339 ExcludedContainerTypes))
347 diag(Ctx.
Var.getLocation(),
348 "the %select{|const qualified }0variable %1 of type %2 is "
350 "from a const reference%select{%select{ but is only used as const "
351 "reference|}0| but is never used}3; consider "
352 "%select{making it a const reference|removing the statement}3")
353 << Ctx.
Var.getType().isConstQualified() << &Ctx.
Var << Ctx.
Var.getType()
355 maybeIssueFixes(Ctx, Diagnostic);
361 diag(Ctx.
Var.getLocation(),
362 "local copy %0 of the variable %1 of type %2 is never "
364 "| and never used}3; consider %select{avoiding the copy|removing "
367 maybeIssueFixes(Ctx, Diagnostic);
370void UnnecessaryCopyInitializationCheck::maybeIssueFixes(
371 const CheckContext &Ctx, DiagnosticBuilder &Diagnostic) {
382 Options.store(Opts,
"AllowedTypes",
384 Options.store(Opts,
"ExcludedContainerTypes",
static cl::opt< bool > Fix("fix", desc(R"(
Apply suggested fixes. Without -fix-errors
clang-tidy will bail out if any compilation
errors were found.
)"), cl::init(false), cl::cat(ClangTidyCategory))
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
AST_MATCHER_FUNCTION_P(ast_matchers::internal::Matcher< Stmt >, comparisonOperatorWithCallee, ast_matchers::internal::Matcher< Decl >, FuncDecl)
inline ::clang::ast_matchers::internal::Matcher< NamedDecl > matchesAnyListedRegexName(llvm::ArrayRef< StringRef > NameList)
SmallPtrSet< const DeclRefExpr *, 16 > allDeclRefExprs(const VarDecl &VarDecl, const Stmt &Stmt, ASTContext &Context)
Returns set of all DeclRefExprs to VarDecl within Stmt.
bool isOnlyUsedAsConst(const VarDecl &Var, const Stmt &Stmt, ASTContext &Context, int Indirections)
Returns true if all DeclRefExpr to the variable within Stmt do not modify it. See constReferenceDeclR...
FixItHint changeVarDeclToReference(const VarDecl &Var, ASTContext &Context)
Creates fix to make VarDecl a reference by adding &.
std::optional< FixItHint > addQualifierToVarDecl(const VarDecl &Var, const ASTContext &Context, Qualifiers::TQ Qualifier, QualifierTarget QualTarget, QualifierPolicy QualPolicy)
Creates fix to qualify VarDecl with the specified Qualifier. Requires that Var is isolated in written...
std::optional< Token > findNextTokenSkippingComments(SourceLocation Start, const SourceManager &SM, const LangOptions &LangOpts)
std::string serializeStringList(ArrayRef< StringRef > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
llvm::StringMap< ClangTidyValue > OptionMap
static constexpr const char FuncDecl[]