1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
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/.
14 // Warn when a variable is referenced from its own initializer. This is not invalid in general (see
15 // C++17 [basic.life]), but is at least suspicious.
19 class SelfInit
: public loplugin::FilteringPlugin
<SelfInit
>
22 explicit SelfInit(loplugin::InstantiationData
const& data
)
23 : FilteringPlugin(data
)
27 bool TraverseVarDecl(VarDecl
* decl
)
29 decls_
.push_back({ decl
, decl
->getCanonicalDecl() });
30 auto const ret
= FilteringPlugin::TraverseVarDecl(decl
);
35 bool TraverseUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr
* expr
)
37 if (expr
->getKind() == UETT_SizeOf
)
41 return FilteringPlugin::TraverseUnaryExprOrTypeTraitExpr(expr
);
44 bool TraverseCXXTypeidExpr(CXXTypeidExpr
const*) { return true; }
46 bool TraverseCXXNoexceptExpr(CXXNoexceptExpr
const*) { return true; }
48 bool TraverseDecltypeTypeLoc(DecltypeTypeLoc
) { return true; }
50 bool VisitDeclRefExpr(DeclRefExpr
const* expr
)
52 if (ignoreLocation(expr
))
56 for (auto const& i
: decls_
)
58 if (expr
->getDecl()->getCanonicalDecl() == i
.canonical
)
61 DiagnosticsEngine::Warning
,
62 ("referencing a variable during its own initialization is error-prone and thus"
65 << expr
->getSourceRange();
66 report(DiagnosticsEngine::Note
, "variable declared here", i
.current
->getLocation())
67 << i
.current
->getSourceRange();
74 void run() override
{ TraverseDecl(compiler
.getASTContext().getTranslationUnitDecl()); }
78 VarDecl
const* current
;
79 VarDecl
const* canonical
;
82 std::vector
<Decl
> decls_
;
85 loplugin::Plugin::Registration
<SelfInit
> X("selfinit");
88 /* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */