Debian Codegraph @

src/checks/level1/range-loop-reference.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
5 SPDX-FileCopyrightText: 2015 Sergio Martins <[email protected]>
6
7 SPDX-License-Identifier: LGPL-2.0-or-later
8 */
9
10 #include "range-loop-reference.h"
11 #include "FixItUtils.h"
12 #include "PreProcessorVisitor.h"
13 #include "QtUtils.h"
14 #include "StringUtils.h"
15 #include "TypeUtils.h"
16
17 #include <clang/AST/Expr.h>
18 #include <clang/AST/Stmt.h>
19 #include <clang/AST/StmtCXX.h>
20 #include <clang/AST/Type.h>
21 #include <llvm/Support/Casting.h>
22
23 using namespace clang;
24
25 void RangeLoopReference::VisitStmt(clang::Stmt *stmt)
26 {
27 if (auto *rangeLoop = dyn_cast<CXXForRangeStmt>(stmt)) {
28 processForRangeLoop(rangeLoop);
29 }
30 }
31
32 void RangeLoopReference::processForRangeLoop(CXXForRangeStmt *rangeLoop)
33 {
34 Expr *containerExpr = rangeLoop->getRangeInit();
35 if (!containerExpr) {
36 return;
37 }
38
39 QualType qt = containerExpr->getType();
40 const Type *t = qt.getTypePtrOrNull();
41 if (!t || !t->isRecordType()) {
42 return;
43 }
44
45 clazy::QualTypeClassification classif;
46 auto *varDecl = rangeLoop->getLoopVariable();
47 bool success = varDecl && clazy::classifyQualType(m_context, varDecl->getType(), varDecl, /*by-ref*/ classif, rangeLoop);
48 if (!success) {
49 return;
50 }
51
52 if (classif.passNonTriviallyCopyableByConstRef) {
53 std::string msg;
54 const std::string paramStr = clazy::simpleTypeName(varDecl->getType(), lo());
55 msg = "Missing reference in range-for with non trivial type (" + paramStr + ')';
56
57 std::vector<FixItHint> fixits;
58 const bool isConst = varDecl->getType().isConstQualified();
59
60 if (!isConst) {
61 SourceLocation start = varDecl->getBeginLoc();
62 fixits.push_back(clazy::createInsertion(start, "const "));
63 }
64
65 SourceLocation end = varDecl->getLocation();
66 fixits.push_back(clazy::createInsertion(end, "&"));
67
68 // We ignore classif.passSmallTrivialByValue because it doesn't matter, the compiler is able
69 // to optimize it, generating the same assembly, regardless of pass by value.
70 emitWarning(varDecl->getBeginLoc(), msg, fixits);
71 }
72 }