diff options
author | Andrzej Hunt <andrzej@ahunt.org> | 2015-11-21 08:14:05 -0800 |
---|---|---|
committer | Stephan Bergmann <sbergman@redhat.com> | 2016-01-05 11:06:52 +0000 |
commit | 9d0b06e9f728d01a2d2908e1e56cb4220cd414d5 (patch) | |
tree | 072f69061281445cf3591f55592b87402dcd14d9 /compilerplugins | |
parent | d202f851717bb5a8fe5fed98f747a1fd164d3225 (diff) |
new loplugin rangedforcopy - use reference in range based for
Inspired by 6e6ae9803796b120e95f6e89575e03c5fd0ed3c2
Change-Id: Ia0f264d3a6bbf076aa5080e3398683e50bc6ef01
Reviewed-on: https://gerrit.libreoffice.org/20190
Tested-by: Jenkins <ci@libreoffice.org>
Reviewed-by: Stephan Bergmann <sbergman@redhat.com>
Diffstat (limited to 'compilerplugins')
-rw-r--r-- | compilerplugins/clang/rangedforcopy.cxx | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/compilerplugins/clang/rangedforcopy.cxx b/compilerplugins/clang/rangedforcopy.cxx new file mode 100644 index 000000000000..4c86fe34420e --- /dev/null +++ b/compilerplugins/clang/rangedforcopy.cxx @@ -0,0 +1,66 @@ + +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#include <string> +#include <iostream> + +#include "plugin.hxx" +#include "compat.hxx" +#include "clang/AST/CXXInheritance.h" + +// Check that we're not unnecessarily copying variables in a range based for loop +// e.g. "for (OUString a: aList)" results in a copy of each string being made, +// whereas "for (const OUString& a: aList)" does not. + +namespace +{ + +class RangedForCopy: + public RecursiveASTVisitor<RangedForCopy>, public loplugin::Plugin +{ +public: + explicit RangedForCopy(InstantiationData const & data): Plugin(data) {} + + virtual void run() override { + TraverseDecl(compiler.getASTContext().getTranslationUnitDecl()); + } + + bool VisitCXXForRangeStmt( const CXXForRangeStmt* stmt ); +}; + +bool RangedForCopy::VisitCXXForRangeStmt( const CXXForRangeStmt* stmt ) +{ + if (ignoreLocation( stmt )) + return true; + + const VarDecl* varDecl = stmt->getLoopVariable(); + if (!varDecl) + return true; + + const QualType type = varDecl->getType(); + if (type->isRecordType() && !type->isReferenceType() && !type->isPointerType()) + { + std::string name = type.getAsString(); + report( + DiagnosticsEngine::Warning, + "Loop variable passed by value, pass by reference instead, e.g. 'const %0&'", + varDecl->getLocStart()) + << name << varDecl->getSourceRange(); + } + + return true; +} + + +loplugin::Plugin::Registration< RangedForCopy > X("rangedforcopy"); + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ |