cid#1555694 COPY_INSTEAD_OF_MOVE
[LibreOffice.git] / compilerplugins / clang / selfinit.cxx
blob3891a5fc724fdbfa63f0b1326c9da57059b17aae
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 */
10 #ifndef LO_CLANG_SHARED_PLUGINS
12 #include <vector>
14 #include "plugin.hxx"
16 // Warn when a variable is referenced from its own initializer. This is not invalid in general (see
17 // C++17 [basic.life]), but is at least suspicious.
19 namespace
21 class SelfInit : public loplugin::FilteringPlugin<SelfInit>
23 public:
24 explicit SelfInit(loplugin::InstantiationData const& data)
25 : FilteringPlugin(data)
29 bool PreTraverseVarDecl(VarDecl* decl)
31 decls_.push_back({ decl, decl->getCanonicalDecl() });
32 return true;
34 bool PostTraverseVarDecl(VarDecl*, bool)
36 decls_.pop_back();
37 return true;
39 bool TraverseVarDecl(VarDecl* decl)
41 PreTraverseVarDecl(decl);
42 auto const ret = FilteringPlugin::TraverseVarDecl(decl);
43 PostTraverseVarDecl(decl, ret);
44 return ret;
47 bool PreTraverseUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr* expr)
49 if (expr->getKind() == UETT_SizeOf)
50 return false;
51 return true;
53 bool TraverseUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr* expr)
55 if (PreTraverseUnaryExprOrTypeTraitExpr(expr))
56 return FilteringPlugin::TraverseUnaryExprOrTypeTraitExpr(expr);
57 return true;
60 bool TraverseCXXTypeidExpr(CXXTypeidExpr*) { return true; }
61 bool PreTraverseCXXTypeidExpr(CXXTypeidExpr*) { return false; }
63 bool TraverseCXXNoexceptExpr(CXXNoexceptExpr*) { return true; }
64 bool PreTraverseCXXNoexceptExpr(CXXNoexceptExpr*) { return false; }
66 bool TraverseDecltypeTypeLoc(DecltypeTypeLoc) { return true; }
67 bool PreTraverseDecltypeTypeLoc(DecltypeTypeLoc) { return false; }
69 bool VisitDeclRefExpr(DeclRefExpr const* expr)
71 if (ignoreLocation(expr))
73 return true;
75 for (auto const& i : decls_)
77 if (expr->getDecl()->getCanonicalDecl() == i.canonical)
79 report(
80 DiagnosticsEngine::Warning,
81 ("referencing a variable during its own initialization is error-prone and thus"
82 " suspicious"),
83 expr->getLocation())
84 << expr->getSourceRange();
85 report(DiagnosticsEngine::Note, "variable declared here", i.current->getLocation())
86 << i.current->getSourceRange();
89 return true;
92 private:
93 void run() override { TraverseDecl(compiler.getASTContext().getTranslationUnitDecl()); }
95 struct Decl
97 VarDecl const* current;
98 VarDecl const* canonical;
101 std::vector<Decl> decls_;
104 loplugin::Plugin::Registration<SelfInit> selfinit("selfinit");
107 #endif // LO_CLANG_SHARED_PLUGINS
109 /* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */