2 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
4 * This file is part of the LibreOffice project.
6 * This Source Code Form is subject to the terms of the Mozilla Public
7 * License, v. 2.0. If a copy of the MPL was not distributed with this
8 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
10 #ifndef LO_CLANG_SHARED_PLUGINS
17 #include "clang/AST/CXXInheritance.h"
19 // Check that we're not unnecessarily copying variables in a range based for loop
20 // e.g. "for (OUString a: aList)" results in a copy of each string being made,
21 // whereas "for (const OUString& a: aList)" does not.
27 public loplugin::FilteringPlugin
<RangedForCopy
>
30 explicit RangedForCopy(loplugin::InstantiationData
const & data
):
31 FilteringPlugin(data
) {}
33 virtual void run() override
{
35 TraverseDecl(compiler
.getASTContext().getTranslationUnitDecl());
38 bool VisitCXXForRangeStmt( const CXXForRangeStmt
* stmt
);
41 bool RangedForCopy::VisitCXXForRangeStmt( const CXXForRangeStmt
* stmt
)
43 if (ignoreLocation( stmt
))
46 const VarDecl
* varDecl
= stmt
->getLoopVariable();
49 if (isa
<DecompositionDecl
>(varDecl
))
51 // Assume that use of a non-reference structured binding is intentional:
55 const QualType type
= varDecl
->getType();
56 if (type
->isRecordType() && !type
->isReferenceType() && !type
->isPointerType())
58 if (loplugin::TypeCheck(type
).Class("__bit_const_reference").StdNamespace())
60 // With libc++ without _LIBCPP_ABI_BITSET_VECTOR_BOOL_CONST_SUBSCRIPT_RETURN_BOOL,
61 // iterating over a const std::vector<bool> non-compliantly uses a variable of some
62 // internal __bit_const_reference class type, rather than of type bool (see
63 // <https://reviews.llvm.org/D123851> "[libc++] Change
64 // vector<bool>::const_iterator::reference to bool in ABIv2"):
67 std::string name
= type
.getAsString();
69 DiagnosticsEngine::Warning
,
70 "Loop variable passed by value, pass by reference instead, e.g. 'const %0&'",
71 varDecl
->getBeginLoc())
72 << name
<< varDecl
->getSourceRange();
79 loplugin::Plugin::Registration
< RangedForCopy
> rangedforcopy("rangedforcopy");
83 #endif // LO_CLANG_SHARED_PLUGINS
85 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */