1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
|
/* -*- 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 <algorithm>
#include <cassert>
#include <deque>
#include <string>
#include <iostream>
#include <fstream>
#include <set>
#include <clang/AST/CXXInheritance.h>
#include "plugin.hxx"
#include "check.hxx"
/**
Simplify boolean expressions involving smart pointers e.g.
if (x.get())
can be
if (x)
*/
//TODO: Make this a shared plugin for Clang 12 (and possibly even for older Clang) again.
namespace
{
class SimplifyPointerToBool : public loplugin::FilteringRewritePlugin<SimplifyPointerToBool>
{
public:
explicit SimplifyPointerToBool(loplugin::InstantiationData const& data)
: FilteringRewritePlugin(data)
{
}
virtual void run() override
{
if (preRun())
TraverseDecl(compiler.getASTContext().getTranslationUnitDecl());
}
bool VisitImplicitCastExpr(ImplicitCastExpr const*);
bool VisitBinaryOperator(BinaryOperator const*);
bool PreTraverseUnaryOperator(UnaryOperator* expr)
{
if (expr->getOpcode() == UO_LNot)
{
contextuallyConvertedExprs_.push_back(expr->getSubExpr()->IgnoreParenImpCasts());
}
return true;
}
bool PostTraverseUnaryOperator(UnaryOperator* expr, bool)
{
if (expr->getOpcode() == UO_LNot)
{
assert(!contextuallyConvertedExprs_.empty());
contextuallyConvertedExprs_.pop_back();
}
return true;
}
bool TraverseUnaryOperator(UnaryOperator* expr)
{
auto res = PreTraverseUnaryOperator(expr);
assert(res);
res = FilteringRewritePlugin::TraverseUnaryOperator(expr);
PostTraverseUnaryOperator(expr, res);
return res;
}
bool PreTraverseBinaryOperator(BinaryOperator* expr)
{
auto const op = expr->getOpcode();
if (op == BO_LAnd || op == BO_LOr)
{
contextuallyConvertedExprs_.push_back(expr->getLHS()->IgnoreParenImpCasts());
contextuallyConvertedExprs_.push_back(expr->getRHS()->IgnoreParenImpCasts());
}
return true;
}
bool PostTraverseBinaryOperator(BinaryOperator* expr, bool)
{
auto const op = expr->getOpcode();
if (op == BO_LAnd || op == BO_LOr)
{
assert(contextuallyConvertedExprs_.size() >= 2);
contextuallyConvertedExprs_.pop_back();
contextuallyConvertedExprs_.pop_back();
}
return true;
}
bool TraverseBinaryOperator(BinaryOperator* expr)
{
auto res = PreTraverseBinaryOperator(expr);
assert(res);
res = FilteringRewritePlugin::TraverseBinaryOperator(expr);
PostTraverseBinaryOperator(expr, res);
return res;
}
bool PreTraverseConditionalOperator(ConditionalOperator* expr)
{
contextuallyConvertedExprs_.push_back(expr->getCond()->IgnoreParenImpCasts());
return true;
}
bool PostTraverseConditionalOperator(ConditionalOperator*, bool)
{
assert(!contextuallyConvertedExprs_.empty());
contextuallyConvertedExprs_.pop_back();
return true;
}
bool TraverseConditionalOperator(ConditionalOperator* expr)
{
auto res = PreTraverseConditionalOperator(expr);
assert(res);
res = FilteringRewritePlugin::TraverseConditionalOperator(expr);
PostTraverseConditionalOperator(expr, res);
return res;
}
bool PreTraverseIfStmt(IfStmt* stmt)
{
contextuallyConvertedExprs_.push_back(stmt->getCond()->IgnoreParenImpCasts());
return true;
}
bool PostTraverseIfStmt(IfStmt*, bool)
{
assert(!contextuallyConvertedExprs_.empty());
contextuallyConvertedExprs_.pop_back();
return true;
}
bool TraverseIfStmt(IfStmt* stmt)
{
auto res = PreTraverseIfStmt(stmt);
assert(res);
res = FilteringRewritePlugin::TraverseIfStmt(stmt);
PostTraverseIfStmt(stmt, res);
return res;
}
bool PreTraverseWhileStmt(WhileStmt* stmt)
{
contextuallyConvertedExprs_.push_back(stmt->getCond()->IgnoreParenImpCasts());
return true;
}
bool PostTraverseWhileStmt(WhileStmt*, bool)
{
assert(!contextuallyConvertedExprs_.empty());
contextuallyConvertedExprs_.pop_back();
return true;
}
bool TraverseWhileStmt(WhileStmt* stmt)
{
auto res = PreTraverseWhileStmt(stmt);
assert(res);
res = FilteringRewritePlugin::TraverseWhileStmt(stmt);
PostTraverseWhileStmt(stmt, res);
return res;
}
bool PreTraverseDoStmt(DoStmt* stmt)
{
contextuallyConvertedExprs_.push_back(stmt->getCond()->IgnoreParenImpCasts());
return true;
}
bool PostTraverseDoStmt(DoStmt*, bool)
{
assert(!contextuallyConvertedExprs_.empty());
contextuallyConvertedExprs_.pop_back();
return true;
}
bool TraverseDoStmt(DoStmt* stmt)
{
auto res = PreTraverseDoStmt(stmt);
assert(res);
res = FilteringRewritePlugin::TraverseDoStmt(stmt);
PostTraverseDoStmt(stmt, res);
return res;
}
bool PreTraverseForStmt(ForStmt* stmt)
{
auto const e = stmt->getCond();
if (e != nullptr)
{
contextuallyConvertedExprs_.push_back(e->IgnoreParenImpCasts());
}
return true;
}
bool PostTraverseForStmt(ForStmt* stmt, bool)
{
if (stmt->getCond() != nullptr)
{
assert(!contextuallyConvertedExprs_.empty());
contextuallyConvertedExprs_.pop_back();
}
return true;
}
bool TraverseForStmt(ForStmt* stmt)
{
auto res = PreTraverseForStmt(stmt);
assert(res);
res = FilteringRewritePlugin::TraverseForStmt(stmt);
PostTraverseForStmt(stmt, res);
return res;
}
private:
bool isContextuallyConverted(Expr const* expr) const
{
return std::find(contextuallyConvertedExprs_.begin(), contextuallyConvertedExprs_.end(),
expr)
!= contextuallyConvertedExprs_.end();
}
// Get the source range starting at the "."or "->" (plus any preceding non-comment white space):
SourceRange getCallSourceRange(CXXMemberCallExpr const* expr) const
{
if (expr->getImplicitObjectArgument() == nullptr)
{
//TODO: Arguably, such a call of a `get` member function from within some member
// function (so that syntactically no caller is mentioned) should already be handled
// differently when reporting it (just "drop the get()" does not make sense), instead of
// being filtered here:
return {};
}
// CXXMemberCallExpr::getExprLoc happens to return the location following the "." or "->":
auto start = compiler.getSourceManager().getSpellingLoc(expr->getExprLoc());
if (!start.isValid())
{
return {};
}
for (;;)
{
start = Lexer::GetBeginningOfToken(start.getLocWithOffset(-1),
compiler.getSourceManager(), compiler.getLangOpts());
auto const s = StringRef(compiler.getSourceManager().getCharacterData(start),
Lexer::MeasureTokenLength(start, compiler.getSourceManager(),
compiler.getLangOpts()));
if (s.empty() || s.startswith("\\\n"))
{
continue;
}
if (s != "." && s != "->")
{
return {};
}
break;
}
for (;;)
{
auto start1 = Lexer::GetBeginningOfToken(
start.getLocWithOffset(-1), compiler.getSourceManager(), compiler.getLangOpts());
auto const s = StringRef(compiler.getSourceManager().getCharacterData(start1),
Lexer::MeasureTokenLength(start1, compiler.getSourceManager(),
compiler.getLangOpts()));
if (!(s.empty() || s.startswith("\\\n")))
{
break;
}
start = start1;
}
return SourceRange(start, compiler.getSourceManager().getSpellingLoc(expr->getEndLoc()));
}
//TODO: There are some more places where an expression is contextually converted to bool, but
// those are probably not relevant for our needs here.
std::deque<Expr const*> contextuallyConvertedExprs_;
};
bool SimplifyPointerToBool::VisitImplicitCastExpr(ImplicitCastExpr const* castExpr)
{
if (ignoreLocation(castExpr))
return true;
if (castExpr->getCastKind() != CK_PointerToBoolean)
return true;
auto memberCallExpr
= dyn_cast<CXXMemberCallExpr>(castExpr->getSubExpr()->IgnoreParenImpCasts());
if (!memberCallExpr)
return true;
auto methodDecl = memberCallExpr->getMethodDecl();
if (!methodDecl || !methodDecl->getIdentifier() || methodDecl->getName() != "get")
return true;
// castExpr->dump();
// methodDecl->getParent()->getTypeForDecl()->dump();
if (!loplugin::isSmartPointerType(memberCallExpr->getImplicitObjectArgument()))
return true;
// if (isa<CXXOperatorCallExpr>(callExpr))
// return true;
// const FunctionDecl* functionDecl;
// if (isa<CXXMemberCallExpr>(callExpr))
// {
// functionDecl = dyn_cast<CXXMemberCallExpr>(callExpr)->getMethodDecl();
// }
// else
// {
// functionDecl = callExpr->getDirectCallee();
// }
// if (!functionDecl)
// return true;
//
// unsigned len = std::min(callExpr->getNumArgs(), functionDecl->getNumParams());
// for (unsigned i = 0; i < len; ++i)
// {
// auto param = functionDecl->getParamDecl(i);
// auto paramTC = loplugin::TypeCheck(param->getType());
// if (!paramTC.AnyBoolean())
// continue;
// auto arg = callExpr->getArg(i)->IgnoreImpCasts();
// auto argTC = loplugin::TypeCheck(arg->getType());
// if (argTC.AnyBoolean())
// continue;
// // sal_Bool is sometimes disguised
// if (isa<SubstTemplateTypeParmType>(arg->getType()))
// if (arg->getType()->getUnqualifiedDesugaredType()->isSpecificBuiltinType(
// clang::BuiltinType::UChar))
// continue;
// if (arg->getType()->isDependentType())
// continue;
// if (arg->getType()->isIntegerType())
// {
// auto ret = getCallValue(arg);
// if (ret.hasValue() && (ret.getValue() == 1 || ret.getValue() == 0))
// continue;
// // something like: priv->m_nLOKFeatures & LOK_FEATURE_DOCUMENT_PASSWORD
// if (isa<BinaryOperator>(arg->IgnoreParenImpCasts()))
// continue;
// // something like: pbEmbolden ? FcTrue : FcFalse
// if (isa<ConditionalOperator>(arg->IgnoreParenImpCasts()))
// continue;
// }
if (isContextuallyConverted(memberCallExpr))
{
if (rewriter)
{
auto const range = getCallSourceRange(memberCallExpr);
if (range.isValid() && removeText(range))
{
return true;
}
}
report(DiagnosticsEngine::Warning, "simplify, drop the get()", memberCallExpr->getExprLoc())
<< memberCallExpr->getSourceRange();
}
else if (isa<ParenExpr>(castExpr->getSubExpr()))
{
if (rewriter)
{
auto const loc
= compiler.getSourceManager().getSpellingLoc(memberCallExpr->getBeginLoc());
auto const range = getCallSourceRange(memberCallExpr);
if (loc.isValid() && range.isValid() && insertText(loc, "bool") && removeText(range))
{
//TODO: atomically only change both or neither
return true;
}
}
report(DiagnosticsEngine::Warning,
"simplify, drop the get() and turn the surrounding parentheses into a functional "
"cast to bool",
memberCallExpr->getExprLoc())
<< memberCallExpr->getSourceRange();
report(DiagnosticsEngine::Note, "surrounding parentheses here",
castExpr->getSubExpr()->getExprLoc())
<< castExpr->getSubExpr()->getSourceRange();
}
else
{
if (rewriter)
{
auto const loc
= compiler.getSourceManager().getSpellingLoc(memberCallExpr->getBeginLoc());
auto const range = getCallSourceRange(memberCallExpr);
if (loc.isValid() && range.isValid() && insertText(loc, "bool(")
&& replaceText(range, ")"))
{
//TODO: atomically only change both or neither
return true;
}
}
report(DiagnosticsEngine::Warning,
"simplify, drop the get() and wrap the expression in a functional cast to bool",
memberCallExpr->getExprLoc())
<< memberCallExpr->getSourceRange();
}
// report(DiagnosticsEngine::Note, "method here", param->getLocation())
// << param->getSourceRange();
return true;
}
bool SimplifyPointerToBool::VisitBinaryOperator(BinaryOperator const* binOp)
{
if (ignoreLocation(binOp))
return true;
auto opCode = binOp->getOpcode();
if (opCode != BO_EQ && opCode != BO_NE)
return true;
const Expr* possibleMemberCall = nullptr;
if (isa<CXXNullPtrLiteralExpr>(binOp->getLHS()->IgnoreParenImpCasts()))
possibleMemberCall = binOp->getRHS();
else if (isa<CXXNullPtrLiteralExpr>(binOp->getRHS()->IgnoreParenImpCasts()))
possibleMemberCall = binOp->getLHS();
else
return true;
auto memberCallExpr = dyn_cast<CXXMemberCallExpr>(possibleMemberCall);
if (!memberCallExpr)
return true;
auto methodDecl = memberCallExpr->getMethodDecl();
if (!methodDecl || !methodDecl->getIdentifier() || methodDecl->getName() != "get")
return true;
if (!loplugin::isSmartPointerType(memberCallExpr->getImplicitObjectArgument()))
return true;
report(DiagnosticsEngine::Warning,
std::string("simplify, convert to ") + (opCode == BO_EQ ? "'!x'" : "'x'"),
binOp->getExprLoc())
<< binOp->getSourceRange();
return true;
}
loplugin::Plugin::Registration<SimplifyPointerToBool> simplifypointertobool("simplifypointertobool",
true);
} // namespace
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|