Debian Codegraph @

src/Utils.cpp

raw
1 /*
2 SPDX-FileCopyrightText: 2015 Klarälvdalens Datakonsult AB a KDAB Group company [email protected]
3 SPDX-FileContributor: Sérgio Martins <[email protected]>
4 SPDX-FileCopyrightText: 2015-2016 Sergio Martins <[email protected]>
5
6 SPDX-License-Identifier: LGPL-2.0-or-later
7 */
8
9 #include "Utils.h"
10 #include "HierarchyUtils.h"
11 #include "StmtBodyRange.h"
12 #include "StringUtils.h"
13 #include "clazy_stl.h"
14
15 #include <clang/AST/Decl.h>
16 #include <clang/AST/DeclBase.h>
17 #include <clang/AST/DeclCXX.h>
18 #include <clang/AST/DeclGroup.h>
19 #include <clang/AST/DeclTemplate.h>
20 #include <clang/AST/Expr.h>
21 #include <clang/AST/ExprCXX.h>
22 #include <clang/AST/OperationKinds.h>
23 #include <clang/AST/Stmt.h>
24 #include <clang/AST/StmtIterator.h>
25 #include <clang/AST/Type.h>
26 #include <clang/Basic/CharInfo.h>
27 #include <clang/Basic/IdentifierTable.h>
28 #include <clang/Basic/LLVM.h>
29 #include <clang/Basic/SourceLocation.h>
30 #include <clang/Basic/SourceManager.h>
31 #include <clang/Lex/Lexer.h>
32 #include <clang/Lex/Token.h>
33 #include <llvm/Support/Casting.h>
34
35 #include <cctype>
36 #include <iterator>
37 #include <utility>
38
39 namespace clang
40 {
41 class LangOptions;
42 } // namespace clang
43
44 using namespace clang;
45
46 bool Utils::hasConstexprCtor(CXXRecordDecl *decl)
47 {
48 return std::ranges::any_of(decl->ctors(), [](CXXConstructorDecl *ctor) {
49 return ctor->isConstexpr();
50 });
51 }
52
53 CXXRecordDecl *Utils::namedCastInnerDecl(CXXNamedCastExpr *staticOrDynamicCast)
54 {
55 Expr *e = staticOrDynamicCast->getSubExpr();
56 if (!e) {
57 return nullptr;
58 }
59 if (auto *implicitCast = dyn_cast<ImplicitCastExpr>(e)) {
60 // Sometimes it's automatically cast to base
61 if (implicitCast->getCastKind() == CK_DerivedToBase) {
62 e = implicitCast->getSubExpr();
63 }
64 }
65
66 QualType qt = e->getType();
67 const Type *t = qt.getTypePtrOrNull();
68 if (!t) {
69 return nullptr;
70 }
71 QualType qt2 = t->getPointeeType();
72 const Type *t2 = qt2.getTypePtrOrNull();
73 if (!t2) {
74 return nullptr;
75 }
76 return t2->getAsCXXRecordDecl();
77 }
78
79 CXXRecordDecl *Utils::namedCastOuterDecl(CXXNamedCastExpr *staticOrDynamicCast)
80 {
81 QualType qt = staticOrDynamicCast->getTypeAsWritten();
82 const Type *t = qt.getTypePtrOrNull();
83 QualType qt2 = t->getPointeeType();
84 const Type *t2 = qt2.getTypePtrOrNull();
85 if (!t2) {
86 return nullptr;
87 }
88 return t2->getAsCXXRecordDecl();
89 }
90
91 bool Utils::allChildrenMemberCallsConst(Stmt *stm)
92 {
93 if (!stm) {
94 return false;
95 }
96
97 auto *expr = dyn_cast<MemberExpr>(stm);
98
99 if (expr) {
100 auto *methodDecl = dyn_cast<CXXMethodDecl>(expr->getMemberDecl());
101 if (methodDecl && !methodDecl->isConst()) {
102 return false;
103 }
104 }
105
106 const auto children = stm->children();
107 return std::all_of(children.begin(), children.end(), [](Stmt *child) {
108 return allChildrenMemberCallsConst(child);
109 });
110 }
111
112 bool Utils::childsHaveSideEffects(Stmt *stm)
113 {
114 if (!stm) {
115 return false;
116 }
117
118 auto *unary = dyn_cast<UnaryOperator>(stm);
119 if (unary && (unary->isIncrementOp() || unary->isDecrementOp())) {
120 return true;
121 }
122
123 auto *binary = dyn_cast<BinaryOperator>(stm);
124 if (binary && (binary->isAssignmentOp() || binary->isShiftAssignOp() || binary->isCompoundAssignmentOp())) {
125 return true;
126 }
127
128 static const std::vector<StringRef> method_blacklist = {
129 "isDestroyed",
130 "isRecursive", // TODO: Use qualified name instead ?
131 "q_func",
132 "d_func",
133 "begin",
134 "end",
135 "data",
136 "fragment",
137 "glIsRenderbuffer",
138 };
139
140 auto *memberCall = dyn_cast<MemberExpr>(stm);
141 if (memberCall) {
142 auto *methodDecl = dyn_cast<CXXMethodDecl>(memberCall->getMemberDecl());
143 if (methodDecl && !methodDecl->isConst() && !methodDecl->isStatic() && !clazy::contains(method_blacklist, clazy::name(methodDecl))) {
144 return true;
145 }
146 }
147
148 /* // too many false positives, qIsFinite() etc for example
149 auto callExpr = dyn_cast<CallExpr>(stm);
150 if (callExpr) {
151 FunctionDecl *callee = callExpr->getDirectCallee();
152 if (callee && callee->isGlobal())
153 return true;
154 }*/
155
156 return clazy::any_of(stm->children(), childsHaveSideEffects);
157 }
158
159 CXXRecordDecl *Utils::recordFromVarDecl(Decl *decl)
160 {
161 auto *varDecl = dyn_cast<VarDecl>(decl);
162 if (!varDecl) {
163 return nullptr;
164 }
165
166 QualType qt = varDecl->getType();
167 const Type *t = qt.getTypePtrOrNull();
168 if (!t) {
169 return nullptr;
170 }
171
172 return t->getAsCXXRecordDecl();
173 }
174
175 ClassTemplateSpecializationDecl *Utils::templateSpecializationFromVarDecl(Decl *decl)
176 {
177 auto *record = recordFromVarDecl(decl);
178 if (record) {
179 return dyn_cast<ClassTemplateSpecializationDecl>(record);
180 }
181
182 return nullptr;
183 }
184
185 ValueDecl *Utils::valueDeclForMemberCall(CXXMemberCallExpr *memberCall)
186 {
187 if (!memberCall) {
188 return nullptr;
189 }
190
191 Expr *implicitObject = memberCall->getImplicitObjectArgument();
192 if (!implicitObject) {
193 return nullptr;
194 }
195
196 auto *declRefExpr = dyn_cast<DeclRefExpr>(implicitObject);
197 auto *memberExpr = dyn_cast<MemberExpr>(implicitObject);
198 if (declRefExpr) {
199 return declRefExpr->getDecl();
200 }
201 if (memberExpr) {
202 return memberExpr->getMemberDecl();
203 }
204
205 // Maybe there's an implicit cast in between..
206 auto memberExprs = clazy::getStatements<MemberExpr>(implicitObject, nullptr, {}, /**depth=*/1, /*includeParent=*/true);
207 auto declRefs = clazy::getStatements<DeclRefExpr>(implicitObject, nullptr, {}, /**depth=*/1, /*includeParent=*/true);
208
209 if (!memberExprs.empty()) {
210 return memberExprs.at(0)->getMemberDecl();
211 }
212
213 if (!declRefs.empty()) {
214 return declRefs.at(0)->getDecl();
215 }
216
217 return nullptr;
218 }
219
220 ValueDecl *Utils::valueDeclForOperatorCall(CXXOperatorCallExpr *operatorCall)
221 {
222 if (!operatorCall) {
223 return nullptr;
224 }
225
226 // CXXOperatorCallExpr doesn't have API to access the value decl.
227 // By inspecting several ASTs I noticed it's always in the 2nd child
228
229 Stmt *child2 = clazy::childAt(operatorCall, 1);
230 if (!child2) {
231 return nullptr;
232 }
233
234 if (auto *memberExpr = dyn_cast<MemberExpr>(child2)) {
235 return memberExpr->getMemberDecl();
236 } else {
237 std::vector<DeclRefExpr *> refs;
238 clazy::getChilds<DeclRefExpr>(child2, refs);
239 if (refs.size() == 1) {
240 return refs[0]->getDecl();
241 }
242 }
243
244 return nullptr;
245 }
246
247 clang::ValueDecl *Utils::valueDeclForCallExpr(clang::CallExpr *expr)
248 {
249 if (auto *memberExpr = dyn_cast<CXXMemberCallExpr>(expr)) {
250 return valueDeclForMemberCall(memberExpr);
251 }
252 if (auto *operatorExpr = dyn_cast<CXXOperatorCallExpr>(expr)) {
253 return valueDeclForOperatorCall(operatorExpr);
254 }
255
256 return nullptr;
257 }
258
259 static bool referencesVar(Stmt *s, const VarDecl *varDecl)
260 {
261 // look for a DeclRefExpr that references varDecl
262 while (s) {
263 auto it = s->child_begin();
264 Stmt *child = it == s->child_end() ? nullptr : *it;
265 if (auto *declRef = dyn_cast_or_null<DeclRefExpr>(child)) {
266 if (declRef->getDecl() == varDecl) {
267 return true;
268 }
269 }
270 s = child;
271 }
272
273 return false;
274 }
275
276 bool Utils::containsNonConstMemberCall(clang::ParentMap * /*map*/, Stmt *body, const VarDecl *varDecl)
277 {
278 if (!varDecl) {
279 return false;
280 }
281
282 std::vector<CXXMemberCallExpr *> memberCallExprs;
283 clazy::getChilds<CXXMemberCallExpr>(body, memberCallExprs);
284 for (auto *memberCall : memberCallExprs) {
285 CXXMethodDecl *methodDecl = memberCall->getMethodDecl();
286 if (methodDecl && !methodDecl->isConst()) {
287 const ValueDecl *valueDecl = Utils::valueDeclForMemberCall(memberCall);
288 if (valueDecl == varDecl) {
289 return true;
290 }
291 }
292 }
293
294 std::vector<CXXOperatorCallExpr *> operatorCalls;
295 clazy::getChilds<CXXOperatorCallExpr>(body, operatorCalls);
296 for (auto *operatorCall : operatorCalls) {
297 FunctionDecl *fDecl = operatorCall->getDirectCallee();
298 if (fDecl) {
299 auto *methodDecl = dyn_cast<CXXMethodDecl>(fDecl);
300 if (methodDecl && !methodDecl->isConst()) {
301 const ValueDecl *valueDecl = Utils::valueDeclForOperatorCall(operatorCall);
302 if (valueDecl == varDecl) {
303 return true;
304 }
305 }
306 }
307 }
308
309 std::vector<BinaryOperator *> assignmentOperators;
310 clazy::getChilds<BinaryOperator>(body, assignmentOperators);
311 for (auto *op : assignmentOperators) {
312 if (!op->isAssignmentOp()) {
313 continue;
314 }
315
316 if (referencesVar(op, varDecl)) {
317 return true;
318 }
319 }
320
321 return false;
322 }
323
324 template<class T>
325 static bool isArgOfFunc(T expr, FunctionDecl *fDecl, const VarDecl *varDecl, bool byRefOrPtrOnly)
326 {
327 unsigned int param = -1;
328 for (auto arg : expr->arguments()) {
329 ++param;
330 auto refExpr = dyn_cast<DeclRefExpr>(arg);
331 if (!refExpr) {
332 if (clazy::hasChildren(arg)) {
333 Stmt *firstChild = *(arg->child_begin()); // Can be null (bug #362236)
334 refExpr = firstChild ? dyn_cast<DeclRefExpr>(firstChild) : nullptr;
335 if (!refExpr) {
336 continue;
337 }
338 } else {
339 continue;
340 }
341 }
342
343 if (refExpr->getDecl() != varDecl) { // It's our variable ?
344 continue;
345 }
346
347 if (!byRefOrPtrOnly) {
348 // We found it
349 return true;
350 }
351
352 // It is, lets see if the callee takes our variable by const-ref
353 if (param >= fDecl->param_size()) {
354 continue;
355 }
356
357 ParmVarDecl *paramDecl = fDecl->getParamDecl(param);
358 if (!paramDecl) {
359 continue;
360 }
361
362 QualType qt = paramDecl->getType();
363 const clang::Type *t = qt.getTypePtrOrNull();
364 if (!t) {
365 continue;
366 }
367
368 if ((t->isReferenceType() || t->isPointerType()) && !t->getPointeeType().isConstQualified()) {
369 return true; // function receives non-const ref, so our foreach variable can't be const-ref
370 }
371 }
372
373 return false;
374 }
375
376 bool Utils::isPassedToFunction(const StmtBodyRange &bodyRange, const VarDecl *varDecl, bool byRefOrPtrOnly)
377 {
378 if (!bodyRange.isValid()) {
379 return false;
380 }
381
382 Stmt *body = bodyRange.body;
383 std::vector<CallExpr *> callExprs;
384 clazy::getChilds<CallExpr>(body, callExprs);
385 for (CallExpr *callexpr : callExprs) {
386 if (bodyRange.isOutsideRange(callexpr)) {
387 continue;
388 }
389
390 FunctionDecl *fDecl = callexpr->getDirectCallee();
391 if (!fDecl) {
392 continue;
393 }
394
395 if (isArgOfFunc(callexpr, fDecl, varDecl, byRefOrPtrOnly)) {
396 return true;
397 }
398 }
399
400 std::vector<CXXConstructExpr *> constructExprs;
401 clazy::getChilds<CXXConstructExpr>(body, constructExprs);
402 for (CXXConstructExpr *constructExpr : constructExprs) {
403 if (bodyRange.isOutsideRange(constructExpr)) {
404 continue;
405 }
406 FunctionDecl *fDecl = constructExpr->getConstructor();
407 if (isArgOfFunc(constructExpr, fDecl, varDecl, byRefOrPtrOnly)) {
408 return true;
409 }
410 }
411
412 return false;
413 }
414
415 bool Utils::addressIsTaken(Stmt *body, const clang::ValueDecl *valDecl)
416 {
417 if (!body || !valDecl) {
418 return false;
419 }
420
421 auto unaries = clazy::getStatements<UnaryOperator>(body);
422 return std::ranges::any_of(unaries, [valDecl](UnaryOperator *op) {
423 if (op->getOpcode() != clang::UO_AddrOf) {
424 return false;
425 }
426
427 auto *declRef = clazy::getFirstChildOfType<DeclRefExpr>(op);
428 return declRef && declRef->getDecl() == valDecl;
429 });
430 }
431
432 bool Utils::isReturned(Stmt *body, const VarDecl *varDecl)
433 {
434 if (!body) {
435 return false;
436 }
437
438 std::vector<ReturnStmt *> returns;
439 clazy::getChilds<ReturnStmt>(body, returns);
440 for (ReturnStmt *returnStmt : returns) {
441 Expr *retValue = returnStmt->getRetValue();
442 if (!retValue) {
443 continue;
444 }
445 auto *declRef = clazy::unpeal<DeclRefExpr>(retValue, clazy::IgnoreImplicitCasts);
446 if (!declRef) {
447 continue;
448 }
449 if (declRef->getDecl() == varDecl) {
450 return true;
451 }
452 }
453
454 return false;
455 }
456
457 bool Utils::isAssignedTo(Stmt *body, const VarDecl *varDecl)
458 {
459 if (!body) {
460 return false;
461 }
462
463 std::vector<BinaryOperator *> operatorCalls;
464 clazy::getChilds<BinaryOperator>(body, operatorCalls);
465 for (BinaryOperator *binaryOperator : operatorCalls) {
466 if (binaryOperator->getOpcode() != clang::BO_Assign) {
467 continue;
468 }
469
470 Expr *rhs = binaryOperator->getRHS();
471 auto *declRef = clazy::unpeal<DeclRefExpr>(rhs, clazy::IgnoreImplicitCasts);
472 if (!declRef) {
473 continue;
474 }
475
476 if (declRef->getDecl() == varDecl) {
477 return true;
478 }
479 }
480
481 return false;
482 }
483
484 bool Utils::isAssignedFrom(Stmt *body, const VarDecl *varDecl)
485 {
486 if (!body) {
487 return false;
488 }
489
490 std::vector<CXXOperatorCallExpr *> operatorCalls;
491 clazy::getChilds<CXXOperatorCallExpr>(body, operatorCalls);
492 for (CXXOperatorCallExpr *operatorExpr : operatorCalls) {
493 FunctionDecl *fDecl = operatorExpr->getDirectCallee();
494 if (!fDecl) {
495 continue;
496 }
497
498 auto *methodDecl = dyn_cast<CXXMethodDecl>(fDecl);
499 if (methodDecl && methodDecl->isCopyAssignmentOperator()) {
500 const ValueDecl *valueDecl = Utils::valueDeclForOperatorCall(operatorExpr);
501 if (valueDecl == varDecl) {
502 return true;
503 }
504 }
505 }
506
507 return false;
508 }
509
510 bool Utils::callHasDefaultArguments(clang::CallExpr *expr)
511 {
512 std::vector<clang::CXXDefaultArgExpr *> exprs;
513 clazy::getChilds<clang::CXXDefaultArgExpr>(expr, exprs, 1);
514 return !exprs.empty();
515 }
516
517 bool Utils::containsStringLiteral(Stmt *stm, bool allowEmpty, int depth)
518 {
519 if (!stm) {
520 return false;
521 }
522
523 std::vector<StringLiteral *> stringLiterals;
524 clazy::getChilds<StringLiteral>(stm, stringLiterals, depth);
525
526 if (allowEmpty) {
527 return !stringLiterals.empty();
528 }
529
530 for (StringLiteral *sl : stringLiterals) {
531 if (sl->getLength() > 0) {
532 return true;
533 }
534 }
535
536 return false;
537 }
538
539 bool Utils::ternaryOperatorIsOfStringLiteral(ConditionalOperator *ternary)
540 {
541 bool skipFirst = true;
542 for (auto *child : ternary->children()) {
543 if (skipFirst) {
544 skipFirst = false;
545 continue;
546 }
547
548 if (isa<StringLiteral>(child)) {
549 continue;
550 }
551
552 auto *arrayToPointerDecay = dyn_cast<ImplicitCastExpr>(child);
553 if (!arrayToPointerDecay || !isa<StringLiteral>(*(arrayToPointerDecay->child_begin()))) {
554 return false;
555 }
556 }
557
558 return true;
559 }
560
561 bool Utils::isAssignOperator(CXXOperatorCallExpr *op, StringRef className, StringRef argumentType, const clang::LangOptions &lo)
562 {
563 if (!op) {
564 return false;
565 }
566
567 FunctionDecl *functionDecl = op->getDirectCallee();
568 if (!functionDecl || functionDecl->param_size() != 1) {
569 return false;
570 }
571
572 if (!className.empty()) {
573 auto *methodDecl = dyn_cast<clang::CXXMethodDecl>(functionDecl);
574 if (!clazy::isOfClass(methodDecl, className)) {
575 return false;
576 }
577 }
578
579 if (functionDecl->getOverloadedOperator() != clang::OO_Equal) {
580 return false;
581 }
582
583 if (!argumentType.empty() && !clazy::hasArgumentOfType(functionDecl, argumentType, lo)) {
584 return false;
585 }
586
587 return true;
588 }
589
590 bool Utils::isImplicitCastTo(Stmt *s, const std::string &className)
591 {
592 auto *expr = dyn_cast<ImplicitCastExpr>(s);
593 if (!expr) {
594 return false;
595 }
596
597 const auto *record = expr->getBestDynamicClassType();
598 return record && clazy::name(record) == className;
599 }
600
601 bool Utils::isInsideOperatorCall(ParentMap *map, Stmt *s, const std::vector<StringRef> &anyOf)
602 {
603 if (!s) {
604 return false;
605 }
606
607 auto *oper = dyn_cast<CXXOperatorCallExpr>(s);
608 if (oper) {
609 auto *func = oper->getDirectCallee();
610 if (func) {
611 if (anyOf.empty()) {
612 return true;
613 }
614
615 auto *method = dyn_cast<CXXMethodDecl>(func);
616 if (method) {
617 auto *record = method->getParent();
618 if (record && clazy::contains(anyOf, clazy::name(record))) {
619 return true;
620 }
621 }
622 }
623 }
624
625 return isInsideOperatorCall(map, clazy::parent(map, s), anyOf);
626 }
627
628 bool Utils::insideCTORCall(ParentMap *map, Stmt *s, const std::vector<llvm::StringRef> &anyOf)
629 {
630 if (!s) {
631 return false;
632 }
633
634 auto *expr = dyn_cast<CXXConstructExpr>(s);
635 if (expr && expr->getConstructor() && clazy::contains(anyOf, clazy::name(expr->getConstructor()))) {
636 return true;
637 }
638
639 return insideCTORCall(map, clazy::parent(map, s), anyOf);
640 }
641
642 bool Utils::presumedLocationsEqual(const clang::PresumedLoc &l1, const clang::PresumedLoc &l2)
643 {
644 return l1.isValid() && l2.isValid() && l1.getColumn() == l2.getColumn() && l1.getLine() == l2.getLine()
645 && StringRef(l1.getFilename()) == StringRef(l2.getFilename());
646 }
647
648 CXXRecordDecl *Utils::isMemberVariable(ValueDecl *decl)
649 {
650 return decl ? dyn_cast<CXXRecordDecl>(decl->getDeclContext()) : nullptr;
651 }
652
653 std::vector<CXXMethodDecl *> Utils::methodsFromString(const CXXRecordDecl *record, const std::string &methodName)
654 {
655 if (!record) {
656 return {};
657 }
658
659 std::vector<CXXMethodDecl *> methods;
660 std::ranges::copy_if(record->methods(), std::back_inserter(methods), [&methodName](CXXMethodDecl *method) {
661 return clazy::name(method) == methodName;
662 });
663
664 // Also include the base classes
665 for (auto base : record->bases()) {
666 if (const Type *t = base.getType().getTypePtrOrNull()) {
667 auto baseMethods = methodsFromString(t->getAsCXXRecordDecl(), methodName);
668 std::ranges::copy(baseMethods, std::back_inserter(methods));
669 }
670 }
671
672 return methods;
673 }
674
675 const CXXRecordDecl *Utils::recordForMemberCall(CXXMemberCallExpr *call, std::string &implicitCallee)
676 {
677 implicitCallee.clear();
678 Expr *implicitArgument = call->getImplicitObjectArgument();
679 if (!implicitArgument) {
680 return nullptr;
681 }
682
683 Stmt *s = implicitArgument;
684 while (s) {
685 if (auto *declRef = dyn_cast<DeclRefExpr>(s)) {
686 if (declRef->getDecl()) {
687 implicitCallee = declRef->getDecl()->getNameAsString();
688 QualType qt = declRef->getDecl()->getType();
689 return qt->getPointeeCXXRecordDecl();
690 }
691 return nullptr;
692
693 } else if (auto *thisExpr = dyn_cast<CXXThisExpr>(s)) {
694 implicitCallee = "this";
695 return thisExpr->getType()->getPointeeCXXRecordDecl();
696 } else if (auto *memberExpr = dyn_cast<MemberExpr>(s)) {
697 auto *decl = memberExpr->getMemberDecl();
698 if (decl) {
699 implicitCallee = decl->getNameAsString();
700 QualType qt = decl->getType();
701 return qt->getPointeeCXXRecordDecl();
702 }
703 return nullptr;
704 }
705
706 s = s->child_begin() == s->child_end() ? nullptr : *(s->child_begin());
707 }
708
709 return nullptr;
710 }
711
712 bool Utils::isAscii(StringLiteral *lt)
713 {
714 // 'é' for some reason has isAscii() == true, so also call containsNonAsciiOrNull
715 return lt && lt->isOrdinary() && !lt->containsNonAsciiOrNull();
716 }
717
718 bool Utils::isInDerefExpression(Stmt *s, ParentMap *map)
719 {
720 if (!s) {
721 return false;
722 }
723
724 Stmt *p = s;
725 do {
726 p = clazy::parent(map, p);
727 auto *op = p ? dyn_cast<CXXOperatorCallExpr>(p) : nullptr;
728 if (op && op->getOperator() == OO_Star) {
729 return op;
730 }
731 } while (p);
732
733 return false;
734 }
735
736 std::vector<CallExpr *> Utils::callListForChain(CallExpr *lastCallExpr)
737 {
738 if (!lastCallExpr) {
739 return {};
740 }
741
742 const bool isOperator = isa<CXXOperatorCallExpr>(lastCallExpr);
743 std::vector<CallExpr *> callexprs = {lastCallExpr};
744 Stmt *s = lastCallExpr;
745 do {
746 const int childCount = std::distance(s->child_begin(), s->child_end());
747 if (isOperator && childCount > 1 && s == lastCallExpr) {
748 // for operator case, the chained call childs are in the second child
749 s = *(++s->child_begin());
750 } else {
751 s = childCount > 0 ? *s->child_begin() : nullptr;
752 }
753
754 if (s) {
755 auto *callExpr = dyn_cast<CallExpr>(s);
756 if (callExpr && callExpr->getCalleeDecl()) {
757 callexprs.push_back(callExpr);
758 } else if (auto *memberExpr = dyn_cast<MemberExpr>(s)) {
759 if (isa<FieldDecl>(memberExpr->getMemberDecl())) {
760 break; // accessing a public member via . or -> breaks the chain
761 }
762 } else if (isa<ConditionalOperator>(s)) {
763 // Gets very greasy with conditional operators
764 // This would match: (should() ? container1 : container2).append()
765 // and it would return { append(), should()}
766 break;
767 }
768 }
769 } while (s);
770
771 return callexprs;
772 }
773
774 CXXRecordDecl *Utils::rootBaseClass(CXXRecordDecl *derived)
775 {
776 if (!derived || derived->getNumBases() == 0) {
777 return derived;
778 }
779
780 CXXBaseSpecifier *base = derived->bases_begin();
781 CXXRecordDecl *record = base->getType()->getAsCXXRecordDecl();
782
783 return record ? rootBaseClass(record) : derived;
784 }
785
786 CXXConstructorDecl *Utils::copyCtor(const CXXRecordDecl *record)
787 {
788 for (auto *ctor : record->ctors()) {
789 if (ctor->isCopyConstructor()) {
790 return ctor;
791 }
792 }
793
794 return nullptr;
795 }
796
797 CXXMethodDecl *Utils::copyAssign(const CXXRecordDecl *record)
798 {
799 for (auto *copyAssign : record->methods()) {
800 if (copyAssign->isCopyAssignmentOperator()) {
801 return copyAssign;
802 }
803 }
804
805 return nullptr;
806 }
807
808 bool Utils::hasMember(CXXRecordDecl *record, const std::string &memberTypeName)
809 {
810 if (!record) {
811 return false;
812 }
813
814 for (auto *field : record->fields()) {
815 field->getParent()->getNameAsString();
816 QualType qt = field->getType();
817 const Type *t = qt.getTypePtrOrNull();
818 if (t && t->getAsCXXRecordDecl()) {
819 const CXXRecordDecl *rec = t->getAsCXXRecordDecl();
820 if (clazy::name(rec) == memberTypeName) {
821 return true;
822 }
823 }
824 }
825
826 return false;
827 }
828
829 bool Utils::isInitializedExternally(clang::VarDecl *varDecl)
830 {
831 if (!varDecl) {
832 return false;
833 }
834
835 DeclContext *context = varDecl->getDeclContext();
836 auto *fDecl = context ? dyn_cast<FunctionDecl>(context) : nullptr;
837 Stmt *body = fDecl ? fDecl->getBody() : nullptr;
838 if (!body) {
839 return false;
840 }
841
842 std::vector<DeclStmt *> declStmts;
843 clazy::getChilds<DeclStmt>(body, declStmts);
844 for (DeclStmt *declStmt : declStmts) {
845 if (referencesVarDecl(declStmt, varDecl)) {
846 std::vector<DeclRefExpr *> declRefs;
847
848 clazy::getChilds<DeclRefExpr>(declStmt, declRefs);
849 if (!declRefs.empty()) {
850 return true;
851 }
852
853 std::vector<CallExpr *> callExprs;
854 clazy::getChilds<CallExpr>(declStmt, callExprs);
855 if (!callExprs.empty()) {
856 return true;
857 }
858 }
859 }
860
861 return false;
862 }
863
864 bool Utils::functionHasEmptyBody(clang::FunctionDecl *func)
865 {
866 Stmt *body = func ? func->getBody() : nullptr;
867 return !clazy::hasChildren(body);
868 }
869
870 clang::Expr *Utils::isWriteOperator(Stmt *stm)
871 {
872 if (!stm) {
873 return nullptr;
874 }
875
876 if (auto *up = dyn_cast<UnaryOperator>(stm)) {
877 auto opcode = up->getOpcode();
878 if (opcode == clang::UO_AddrOf || opcode == clang::UO_Deref) {
879 return nullptr;
880 }
881
882 return up->getSubExpr();
883 }
884
885 if (auto *bp = dyn_cast<BinaryOperator>(stm)) {
886 return bp->getLHS();
887 }
888
889 return nullptr;
890 }
891
892 bool Utils::referencesVarDecl(clang::DeclStmt *declStmt, clang::VarDecl *varDecl)
893 {
894 if (!declStmt || !varDecl) {
895 return false;
896 }
897
898 if (declStmt->isSingleDecl() && declStmt->getSingleDecl() == varDecl) {
899 return true;
900 }
901
902 return std::ranges::any_of(declStmt->getDeclGroup(), [varDecl](Decl *decl) {
903 return varDecl == decl;
904 });
905 }
906
907 UserDefinedLiteral *Utils::userDefinedLiteral(Stmt *stm, const std::string &type, const clang::LangOptions &lo)
908 {
909 auto *udl = dyn_cast<UserDefinedLiteral>(stm);
910 if (!udl) {
911 udl = clazy::getFirstChildOfType<UserDefinedLiteral>(stm);
912 }
913
914 if (udl && clazy::returnTypeName(udl, lo) == type) {
915 return udl;
916 }
917
918 return nullptr;
919 }
920
921 clang::ArrayRef<clang::ParmVarDecl *> Utils::functionParameters(clang::FunctionDecl *func)
922 {
923 return func->parameters();
924 }
925
926 std::vector<CXXCtorInitializer *> Utils::ctorInitializer(CXXConstructorDecl *ctor, clang::ParmVarDecl *param)
927 {
928 if (!ctor) {
929 return {};
930 }
931
932 std::vector<CXXCtorInitializer *> result;
933
934 for (auto it = ctor->init_begin(), end = ctor->init_end(); it != end; ++it) {
935 auto *ctorInit = *it;
936 std::vector<DeclRefExpr *> declRefs;
937 clazy::getChilds(ctorInit->getInit(), declRefs);
938 for (auto *declRef : declRefs) {
939 if (declRef->getDecl() == param) {
940 result.push_back(ctorInit);
941 break;
942 }
943 }
944 }
945
946 return result;
947 }
948
949 bool Utils::ctorInitializerContainsMove(CXXCtorInitializer *init)
950 {
951 if (!init) {
952 return false;
953 }
954
955 std::vector<CallExpr *> calls;
956 clazy::getChilds(init->getInit(), calls);
957
958 for (auto *call : calls) {
959 if (FunctionDecl *funcDecl = call->getDirectCallee()) {
960 auto name = funcDecl->getQualifiedNameAsString();
961 if (name == "std::move" || name == "std::__1::move") {
962 return true;
963 }
964 }
965 }
966
967 return false;
968 }
969
970 bool Utils::ctorInitializerContainsMove(const std::vector<CXXCtorInitializer *> &ctorInits)
971 {
972 return std::ranges::any_of(ctorInits, [](CXXCtorInitializer *ctorInit) {
973 return Utils::ctorInitializerContainsMove(ctorInit);
974 });
975 }
976
977 std::string Utils::filenameForLoc(SourceLocation loc, const clang::SourceManager &sm)
978 {
979 if (loc.isMacroID()) {
980 loc = sm.getExpansionLoc(loc);
981 }
982
983 const std::string filename = sm.getFilename(loc).str();
984 auto splitted = clazy::splitString(filename, '/');
985 if (splitted.empty()) {
986 return {};
987 }
988
989 return splitted[splitted.size() - 1];
990 }
991
992 SourceLocation Utils::locForNextToken(SourceLocation loc, const clang::SourceManager &sm, const clang::LangOptions &lo)
993 {
994 std::pair<FileID, unsigned> locInfo = sm.getDecomposedLoc(loc);
995 bool InvalidTemp = false;
996 StringRef File = sm.getBufferData(locInfo.first, &InvalidTemp);
997 if (InvalidTemp) {
998 return {};
999 }
1000
1001 const char *TokenBegin = File.data() + locInfo.second;
1002 Lexer lexer(sm.getLocForStartOfFile(locInfo.first), lo, File.begin(), TokenBegin, File.end());
1003
1004 Token Tok;
1005 lexer.LexFromRawLexer(Tok);
1006
1007 SourceLocation TokenLoc = Tok.getLocation();
1008
1009 // Calculate how much whitespace needs to be skipped if any.
1010 unsigned NumWhitespaceChars = 0;
1011 const char *TokenEnd = sm.getCharacterData(TokenLoc) + Tok.getLength();
1012 unsigned char C = *TokenEnd;
1013 while (isHorizontalWhitespace(C)) {
1014 C = *(++TokenEnd);
1015 NumWhitespaceChars++;
1016 }
1017
1018 // Skip \r, \n, \r\n, or \n\r
1019 if (C == '\n' || C == '\r') {
1020 char PrevC = C;
1021 C = *(++TokenEnd);
1022 NumWhitespaceChars++;
1023 if ((C == '\n' || C == '\r') && C != PrevC) {
1024 NumWhitespaceChars++;
1025 }
1026 }
1027
1028 return loc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
1029 }
1030
1031 bool Utils::literalContainsEscapedBytes(StringLiteral *lt, const SourceManager &sm, const LangOptions &lo)
1032 {
1033 if (!lt) {
1034 return false;
1035 }
1036
1037 // The AST doesn't have the info, we need to ask the Lexer
1038 SourceRange sr = lt->getSourceRange();
1039 CharSourceRange cr = Lexer::getAsCharRange(sr, sm, lo);
1040 const StringRef str = Lexer::getSourceText(cr, sm, lo);
1041
1042 for (int i = 0, size = str.size(); i < size - 1; ++i) {
1043 if (str[i] == '\\') {
1044 auto next = str[i + 1];
1045 if (next == 'U' || next == 'u' || next == 'x' || std::isdigit(next)) {
1046 return true;
1047 }
1048 }
1049 }
1050
1051 return false;
1052 }