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/.
10 #ifndef LO_CLANG_SHARED_PLUGINS
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.
21 class SelfInit
: public loplugin::FilteringPlugin
<SelfInit
>
24 explicit SelfInit(loplugin::InstantiationData
const& data
)
25 : FilteringPlugin(data
)
29 bool PreTraverseVarDecl(VarDecl
* decl
)
31 decls_
.push_back({ decl
, decl
->getCanonicalDecl() });
34 bool PostTraverseVarDecl(VarDecl
*, bool)
39 bool TraverseVarDecl(VarDecl
* decl
)
41 PreTraverseVarDecl(decl
);
42 auto const ret
= FilteringPlugin::TraverseVarDecl(decl
);
43 PostTraverseVarDecl(decl
, ret
);
47 bool PreTraverseUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr
* expr
)
49 if (expr
->getKind() == UETT_SizeOf
)
53 bool TraverseUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr
* expr
)
55 if (PreTraverseUnaryExprOrTypeTraitExpr(expr
))
56 return FilteringPlugin::TraverseUnaryExprOrTypeTraitExpr(expr
);
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
))
75 for (auto const& i
: decls_
)
77 if (expr
->getDecl()->getCanonicalDecl() == i
.canonical
)
80 DiagnosticsEngine::Warning
,
81 ("referencing a variable during its own initialization is error-prone and thus"
84 << expr
->getSourceRange();
85 report(DiagnosticsEngine::Note
, "variable declared here", i
.current
->getLocation())
86 << i
.current
->getSourceRange();
93 void run() override
{ TraverseDecl(compiler
.getASTContext().getTranslationUnitDecl()); }
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: */