1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
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/.
15 // Methods that purely return a local field should be declared in the header and be declared inline.
16 // So that the compiler can elide the function call and turn it into a simple fixed-offset-load instruction.
20 class InlineSimpleMemberFunctions
:
21 public RecursiveASTVisitor
<InlineSimpleMemberFunctions
>, public loplugin::RewritePlugin
24 explicit InlineSimpleMemberFunctions(InstantiationData
const & data
): RewritePlugin(data
) {}
26 virtual void run() override
{ TraverseDecl(compiler
.getASTContext().getTranslationUnitDecl()); }
28 bool VisitCXXMethodDecl(const CXXMethodDecl
* decl
);
30 bool rewrite(const CXXMethodDecl
* functionDecl
);
33 static bool oneAndOnlyOne(clang::Stmt::const_child_range range
) {
37 if ((++range
.first
) != range
.second
) {
44 bool InlineSimpleMemberFunctions::VisitCXXMethodDecl(const CXXMethodDecl
* functionDecl
) {
45 if (ignoreLocation(functionDecl
)) {
48 // no point in doing virtual methods, the compiler always has to generate a vtable entry and a method
49 if (functionDecl
->isVirtual()) {
52 if (functionDecl
->getTemplatedKind() != FunctionDecl::TK_NonTemplate
) {
55 if (!functionDecl
->isInstance()) {
58 if (!functionDecl
->isOutOfLine()) {
61 if( !functionDecl
->hasBody()) {
64 if( functionDecl
->isInlineSpecified()) {
67 if( functionDecl
->getCanonicalDecl()->isInlineSpecified()) {
70 if( functionDecl
->getNameAsString().find("Impl") != std::string::npos
) {
73 // ignore stuff that forms part of the stable URE interface
74 if (isInUnoIncludeFile(compiler
.getSourceManager().getSpellingLoc(
75 functionDecl
->getCanonicalDecl()->getNameInfo().getLoc()))) {
79 // template<class E> E * Sequence<E>::begin() { return getArray(); }
80 if( functionDecl
->getParent()->getDescribedClassTemplate() != nullptr ) {
85 The chain here looks like
92 const CompoundStmt
* compoundStmt
= dyn_cast
< CompoundStmt
>( functionDecl
->getBody() );
93 if (compoundStmt
== nullptr) {
96 if (compoundStmt
->body_begin() == compoundStmt
->body_end()) {
101 const Stmt
* childStmt
= *compoundStmt
->child_begin();
103 if (dyn_cast
<ReturnStmt
>( childStmt
) == nullptr) {
106 if (!oneAndOnlyOne(childStmt
->children())) {
111 /* Don't warn if we see a method definition like
127 childStmt
= *childStmt
->child_begin();
128 if (dyn_cast
<ImplicitCastExpr
>( childStmt
) != nullptr
129 && oneAndOnlyOne( childStmt
->children() ))
131 const Stmt
* childStmt2
= *childStmt
->child_begin();
132 if (dyn_cast
<UnaryOperator
>( childStmt2
) != nullptr
133 && oneAndOnlyOne(childStmt2
->children()))
135 childStmt2
= *childStmt2
->child_begin();
136 if (dyn_cast
<CXXThisExpr
>( childStmt2
) != nullptr
137 && childStmt2
->children().empty())
143 if (dyn_cast
<UnaryOperator
>( childStmt
) != nullptr
144 && oneAndOnlyOne( childStmt
->children() ))
146 const Stmt
* childStmt2
= *childStmt
->child_begin();
147 if (dyn_cast
<CXXThisExpr
>( childStmt2
) != nullptr
148 && childStmt2
->children().empty())
154 /* look for a chains like:
160 childStmt
= *(*compoundStmt
->child_begin())->child_begin();
162 if (dyn_cast
<CallExpr
>( childStmt
) != nullptr)
164 if (dyn_cast
<CXXNewExpr
>( childStmt
) != nullptr)
166 if (dyn_cast
<CXXConstructExpr
>( childStmt
) != nullptr)
168 if (dyn_cast
<ConditionalOperator
>( childStmt
) != nullptr)
170 if (dyn_cast
<BinaryOperator
>( childStmt
) != nullptr)
172 // exclude methods that return fields on incomplete types .e.g the pImpl pattern
173 const MemberExpr
* memberExpr
= dyn_cast
<MemberExpr
>( childStmt
);
174 if (memberExpr
!= nullptr && memberExpr
->getMemberDecl()) {
175 const FieldDecl
* fieldDecl
= dyn_cast
<FieldDecl
>(memberExpr
->getMemberDecl());
176 if (fieldDecl
!= nullptr)
178 // yes, a little bit of a hack. However, it is quite hard to determine if the method
179 // in question is accessing a field via a pImpl pattern.
180 if (fieldDecl
->getType()->isIncompleteType())
182 if (fieldDecl
->getNameAsString().find("Impl") != std::string::npos
)
184 if (fieldDecl
->getNameAsString().find("pImp") != std::string::npos
)
187 if (fieldDecl
->getNameAsString().find("mpGlobalSyncData") != std::string::npos
)
189 std::string s
= fieldDecl
->getType().getAsString();
190 if (s
.find("Impl") != std::string::npos
|| s
.find("pImp") != std::string::npos
|| s
.find("Internal") != std::string::npos
)
194 if (dyn_cast
<CXXThisExpr
>( childStmt
) != nullptr) {
195 if (!rewrite(functionDecl
))
198 DiagnosticsEngine::Warning
,
199 "inlinesimpleaccessmethods",
200 functionDecl
->getSourceRange().getBegin())
201 << functionDecl
->getSourceRange();
202 // display the location of the class member declaration so I don't have to search for it by hand
204 DiagnosticsEngine::Note
,
205 "inlinesimpleaccessmethods",
206 functionDecl
->getCanonicalDecl()->getSourceRange().getBegin())
207 << functionDecl
->getCanonicalDecl()->getSourceRange();
211 if ( childStmt
->children().empty() )
213 childStmt
= *childStmt
->child_begin();
218 static std::string
ReplaceString(std::string subject
, const std::string
& search
,
219 const std::string
& replace
) {
221 while ((pos
= subject
.find(search
, pos
)) != std::string::npos
) {
222 subject
.replace(pos
, search
.length(), replace
);
223 pos
+= replace
.length();
228 bool InlineSimpleMemberFunctions::rewrite(const CXXMethodDecl
* functionDecl
) {
229 if (rewriter
== nullptr) {
232 // Only rewrite declarations in include files if a
233 // definition is also seen, to avoid compilation of a
234 // definition (in a main file only processed later) to fail
235 // with a "mismatch" error before the rewriter had a chance
236 // to act upon the definition.
237 if (!compat::isInMainFile( compiler
.getSourceManager(),
238 compiler
.getSourceManager().getSpellingLoc(
239 functionDecl
->getNameInfo().getLoc()))) {
245 // get the function body contents
246 p1
= compiler
.getSourceManager().getCharacterData( functionDecl
->getBody()->getLocStart() );
247 p2
= compiler
.getSourceManager().getCharacterData( functionDecl
->getBody()->getLocEnd() );
248 std::string
s1( p1
, p2
- p1
+ 1);
250 /* we can't safely move around stuff containing comments, we mess up the resulting code */
251 if ( s1
.find("/*") != std::string::npos
|| s1
.find("//") != std::string::npos
) {
255 // strip linefeeds and any double-spaces, so we have a max of one space between tokens
256 s1
= ReplaceString(s1
, "\r", "");
257 s1
= ReplaceString(s1
, "\n", "");
258 s1
= ReplaceString(s1
, "\t", " ");
259 s1
= ReplaceString(s1
, " ", " ");
260 s1
= ReplaceString(s1
, " ", " ");
261 s1
= ReplaceString(s1
, " ", " ");
264 // scan from the end of the function's body through the trailing whitespace, so we can do a nice clean remove
265 // commented out because for some reason it will sometimes chomp an extra token
266 // SourceLocation endOfRemoveLoc = functionDecl->getBody()->getLocEnd();
268 // endOfRemoveLoc = endOfRemoveLoc.getLocWithOffset(1);
269 // p1 = compiler.getSourceManager().getCharacterData( endOfRemoveLoc );
270 // if (*p1 != ' ' && *p1 != '\r' && *p1 != '\n' && *p1 != '\t')
274 // remove the function's out of line body and declaration
276 opts
.RemoveLineIfEmpty
= true;
277 if (!removeText(SourceRange(functionDecl
->getLocStart(), functionDecl
->getBody()->getLocEnd()), opts
)) {
281 // scan forward until we find the semicolon
282 const FunctionDecl
* canonicalDecl
= functionDecl
->getCanonicalDecl();
283 p1
= compiler
.getSourceManager().getCharacterData( canonicalDecl
->getLocEnd() );
285 while (*p2
!= 0 && *p2
!= ';') p2
++;
287 // insert the function body into the inline function definition (i.e. the one inside the class definition)
288 return replaceText(canonicalDecl
->getLocEnd().getLocWithOffset(p2
- p1
+ 1), 1, s1
);
291 loplugin::Plugin::Registration
< InlineSimpleMemberFunctions
> X("inlinesimplememberfunctions");
295 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */