1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
3 * This file is part of the LibreOffice project.
7 * This file is distributed under the University of Illinois Open Source
8 * License. See LICENSE.TXT for details.
11 #ifndef LO_CLANG_SHARED_PLUGINS
18 #include <unordered_set>
23 Look for places where we are using cow_wrapper, but we are calling a const method on the impl object
24 with a non-const pointer, which means we will unnecessarily trigger a copy.
29 class Cow_Wrapper
: public loplugin::FilteringPlugin
<Cow_Wrapper
>
32 explicit Cow_Wrapper(loplugin::InstantiationData
const& data
)
33 : FilteringPlugin(data
)
37 virtual bool preRun() override
{ return true; }
39 virtual void run() override
42 TraverseDecl(compiler
.getASTContext().getTranslationUnitDecl());
45 bool VisitCXXMemberCallExpr(const CXXMemberCallExpr
*);
48 bool Cow_Wrapper::VisitCXXMemberCallExpr(const CXXMemberCallExpr
* memberCallExpr
)
50 if (ignoreLocation(memberCallExpr
))
52 auto methodDecl
= memberCallExpr
->getMethodDecl();
53 if (!methodDecl
|| !methodDecl
->isConst())
56 auto expr
= memberCallExpr
->getImplicitObjectArgument()->IgnoreImplicit()->IgnoreParens();
57 auto operatorCallExpr
= dyn_cast
<CXXOperatorCallExpr
>(expr
);
59 if (operatorCallExpr
&& operatorCallExpr
->getOperator() == OO_Arrow
)
61 auto arrowMethodDecl
= dyn_cast_or_null
<CXXMethodDecl
>(operatorCallExpr
->getDirectCallee());
64 if (arrowMethodDecl
->isConst())
66 auto dc
= loplugin::DeclCheck(arrowMethodDecl
->getParent())
73 else if (operatorCallExpr
)
75 auto methodDecl2
= dyn_cast_or_null
<CXXMethodDecl
>(operatorCallExpr
->getDirectCallee());
78 auto dc
= loplugin::DeclCheck(methodDecl2
->getParent())
85 else if (auto callExpr
= dyn_cast
<CallExpr
>(expr
))
87 if (!isa
<ImplicitCastExpr
>(callExpr
->getCallee())) // std::as_const shows up as this
89 if (callExpr
->getNumArgs() < 1)
91 auto arg0
= dyn_cast
<CXXOperatorCallExpr
>(callExpr
->getArg(0));
94 auto starMethodDecl
= dyn_cast_or_null
<CXXMethodDecl
>(arg0
->getDirectCallee());
97 auto dc
= loplugin::DeclCheck(starMethodDecl
->getParent())
107 report(DiagnosticsEngine::Warning
,
108 "calling const method on o3tl::cow_wrapper impl class via non-const pointer, rather use "
109 "std::as_const to prevent triggering an unnecessary copy",
110 memberCallExpr
->getBeginLoc())
111 << memberCallExpr
->getSourceRange();
115 loplugin::Plugin::Registration
<Cow_Wrapper
> cow_wrapper("cow_wrapper", true);
119 #endif // LO_CLANG_SHARED_PLUGINS
121 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */