forked from andreasfertig/cppinsights
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsightsHelpers.cpp
446 lines (361 loc) · 15.3 KB
/
InsightsHelpers.cpp
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
445
446
/******************************************************************************
*
* C++ Insights, copyright (C) by Andreas Fertig
* Distributed under an MIT license. See LICENSE for details
*
****************************************************************************/
#include "InsightsHelpers.h"
#include "CodeGenerator.h"
#include "DPrint.h"
#include "InsightsStaticStrings.h"
#include "OutputFormatHelper.h"
//-----------------------------------------------------------------------------
namespace clang::insights {
static const struct CppInsightsPrintingPolicy : PrintingPolicy
{
CppInsightsPrintingPolicy()
: PrintingPolicy{LangOptions{}}
{
adjustForCPlusPlus();
SuppressUnwrittenScope = true;
Alignof = true;
ConstantsAsWritten = true;
AnonymousTagLocations = false; // does remove filename and line for from lambdas in parameters
}
} InsightsPrintingPolicy{};
//-----------------------------------------------------------------------------
static const std::string GetAsCPPStyleString(const QualType& t)
{
return t.getAsString(InsightsPrintingPolicy);
}
//-----------------------------------------------------------------------------
std::string BuildInternalVarName(const std::string& varName)
{
return StrCat("__", varName);
}
//-----------------------------------------------------------------------------
std::string BuildInternalVarName(const std::string& varName, const SourceLocation& loc, const SourceManager& sm)
{
const auto lineNo = sm.getSpellingLineNumber(loc);
return StrCat(BuildInternalVarName(varName), std::to_string(lineNo));
}
//-----------------------------------------------------------------------------
static const LangOptions& GetLangOpts(const ast_matchers::MatchFinder::MatchResult& result)
{
return result.Context->getLangOpts();
}
//-----------------------------------------------------------------------------
SourceLocation FindLocationAfterToken(const SourceLocation loc,
const tok::TokenKind tokenKind,
const ast_matchers::MatchFinder::MatchResult& result)
{
const SourceLocation locEnd =
clang::Lexer::findLocationAfterToken(loc, tokenKind, GetSM(result), GetLangOpts(result), false);
if(locEnd.isValid()) {
return locEnd;
}
return loc;
}
//-----------------------------------------------------------------------------
SourceRange GetSourceRangeAfterToken(const SourceRange range,
const tok::TokenKind tokenKind,
const ast_matchers::MatchFinder::MatchResult& result)
{
SourceLocation locEnd = FindLocationAfterToken(range.getEnd(), tokenKind, result);
if(locEnd.isInvalid()) {
locEnd = range.getEnd();
}
return {range.getBegin(), locEnd};
}
//-----------------------------------------------------------------------------
void InsertBefore(std::string& source, const std::string& find, const std::string& replace)
{
const std::string::size_type i = source.find(find, 0);
if(std::string::npos != i) {
source.insert(i, replace);
}
}
//-----------------------------------------------------------------------------
static void InsertAfter(std::string& source, const std::string& find, const std::string& replace)
{
const std::string::size_type i = source.find(find, 0);
if(std::string::npos != i) {
source.insert(i + find.length(), replace);
}
}
//-----------------------------------------------------------------------------
std::string GetLambdaName(const CXXRecordDecl& lambda)
{
static const std::string lambdaPrefix{"__lambda_"};
const auto& sm = GetSM(lambda);
const auto lineNo = sm.getSpellingLineNumber(lambda.getLocStart());
const auto columnNo = sm.getSpellingColumnNumber(lambda.getLocStart());
return StrCat(lambdaPrefix, std::to_string(lineNo), "_", std::to_string(columnNo));
}
//-----------------------------------------------------------------------------
const QualType GetDesugarType(const QualType& QT)
{
if(QT.getTypePtrOrNull()) {
if(auto declType = QT->getAs<clang::DecltypeType>()) {
return declType->desugar();
}
}
return QT;
}
//-----------------------------------------------------------------------------
const std::string EvaluateAsFloat(const FloatingLiteral& expr)
{
SmallString<16> str{};
expr.getValue().toString(str);
if(std::string::npos == str.find('.')) {
/* in case it is a number like 10.0 toString() seems to leave out the .0. However, as this distinguished
* between an integer and a floating point literal we need that dot. */
str.append(".0");
}
return str.str();
}
//-----------------------------------------------------------------------------
const VarDecl* GetVarDeclFromDeclRefExpr(const DeclRefExpr* declRefExpr)
{
if(nullptr != declRefExpr) {
const auto* valueDecl = declRefExpr->getDecl();
return dyn_cast_or_null<VarDecl>(valueDecl);
}
return nullptr;
}
//-----------------------------------------------------------------------------
namespace details {
static std::string GetQualifiedName(const NamedDecl& decl)
{
std::string name;
llvm::raw_string_ostream stream(name);
decl.printQualifiedName(stream, InsightsPrintingPolicy);
return stream.str();
}
//-----------------------------------------------------------------------------
static std::string GetScope(const DeclContext* declCtx)
{
std::string name{};
if(!declCtx->isTranslationUnit() && !declCtx->isFunctionOrMethod()) {
while(declCtx->isInlineNamespace()) {
declCtx = declCtx->getParent();
}
if(declCtx->isNamespace() || declCtx->getParent()->isTranslationUnit()) {
if(const auto* namespaceDecl = dyn_cast_or_null<NamespaceDecl>(declCtx)) {
name = GetQualifiedName(*namespaceDecl);
name.append("::");
}
}
}
return name;
}
//-----------------------------------------------------------------------------
static std::string GetNameInternal(const QualType& t, const Unqualified unqualified)
{
if(t.getTypePtrOrNull()) {
std::string refOrPointer{};
const RecordType* recordType = [&]() -> const RecordType* {
const auto& ct = t.getCanonicalType();
const auto* ctp = ct.getTypePtrOrNull();
if(const auto* sta = dyn_cast_or_null<RValueReferenceType>(ctp)) {
refOrPointer = "&&";
return dyn_cast_or_null<RecordType>(sta->getPointeeTypeAsWritten().getTypePtrOrNull());
} else if(const auto* ref = dyn_cast_or_null<ReferenceType>(ctp)) {
refOrPointer = "&";
return dyn_cast_or_null<RecordType>(ref->getPointeeTypeAsWritten().getTypePtrOrNull());
} else if(const auto* ptr = dyn_cast_or_null<PointerType>(ctp)) {
refOrPointer = "*";
return dyn_cast_or_null<RecordType>(ptr->getPointeeType().getTypePtrOrNull());
}
return dyn_cast_or_null<RecordType>(ctp);
}();
if(recordType) {
if(const auto* decl = recordType->getDecl()) {
const std::string cvqStr{[&]() {
if(const auto* refType = dyn_cast_or_null<ReferenceType>(t.getTypePtrOrNull())) {
return refType->getPointeeTypeAsWritten().getLocalQualifiers().getAsString();
}
return t.getLocalQualifiers().getAsString();
}()};
if(const auto* tt = dyn_cast_or_null<ClassTemplateSpecializationDecl>(decl)) {
if(const auto* x = t.getBaseTypeIdentifier()) {
OutputFormatHelper ofm{};
if((Unqualified::No == unqualified) && !cvqStr.empty()) {
ofm.Append(cvqStr, " ");
}
ofm.Append(GetScope(decl->getDeclContext()), x->getName());
CodeGenerator codeGenerator{ofm};
codeGenerator.InsertTemplateArgs(*tt);
if(!refOrPointer.empty()) {
ofm.Append(" ", refOrPointer);
}
return ofm.GetString();
}
} else if(const auto* cxxRecordDecl = dyn_cast_or_null<CXXRecordDecl>(decl)) {
if(cxxRecordDecl->isLambda()) {
std::string result{cvqStr};
if(!cvqStr.empty()) {
result += ' ';
}
result += GetLambdaName(*cxxRecordDecl);
if(!refOrPointer.empty()) {
result += ' ';
result += refOrPointer;
}
return result;
}
}
}
}
}
if(Unqualified::Yes == unqualified) {
return GetAsCPPStyleString(t.getUnqualifiedType());
}
return GetAsCPPStyleString(t);
}
//-----------------------------------------------------------------------------
static std::string GetName(const QualType& t, const Unqualified unqualified = Unqualified::No)
{
const auto t2 = GetDesugarType(t);
const auto* at = t2->getContainedAutoType();
if(at && at->isSugared()) {
const auto dt = at->getDeducedType();
// treat LValueReference special at this point. This means we are coming from auto&& and it decayed to an
// l-value reference.
if(dt->isLValueReferenceType()) {
return GetNameInternal(dt, unqualified);
}
}
return GetNameInternal(t, unqualified);
}
} // namespace details
//-----------------------------------------------------------------------------
std::string GetName(const QualType& t, const Unqualified unqualified)
{
return details::GetName(t, unqualified);
}
//-----------------------------------------------------------------------------
std::string GetTypeNameAsParameter(const QualType& t, const std::string& varName, const Unqualified unqualified)
{
const bool isArrayRef = [&]() {
if(const auto* lref = dyn_cast_or_null<LValueReferenceType>(t.getTypePtrOrNull())) {
const auto subType = GetDesugarType(lref->getPointeeType());
const auto& ct = subType.getCanonicalType();
const auto* plainSubType = ct.getTypePtrOrNull();
if(const auto* pt = dyn_cast_or_null<ParenType>(plainSubType)) {
if(pt->getInnerType()->isArrayType()) {
return true;
}
} else if(isa<ConstantArrayType>(plainSubType)) {
return true;
}
}
return false;
}();
std::string typeName = details::GetName(t, unqualified);
// someties we get char const[2]. If we directly insert the typename we end up with char const__var[2] which is not
// a valid type name. Hence check for this condition and, if necessary, insert a space before __var.
auto getSpaceOrEmpty = [&](const std::string& needle) -> std::string {
if(std::string::npos == typeName.find(needle, 0)) {
return " ";
}
return "";
};
if(t->isArrayType() && t->isLValueReferenceType()) {
std::string space = getSpaceOrEmpty(" [");
InsertBefore(typeName, "[", StrCat(space, "(&", varName, ")"));
} else if(t->isArrayType() && !t->isLValueReferenceType()) {
std::string space = getSpaceOrEmpty(" [");
InsertBefore(typeName, "[", StrCat(space, varName));
} else if(isArrayRef) {
if(std::string::npos != typeName.find("(&", 0)) {
InsertAfter(typeName, "(&", varName);
} else {
InsertBefore(typeName, "&[", "(");
InsertAfter(typeName, "(&", StrCat(varName, ")"));
}
} else if(!t->isArrayType() && !varName.empty()) {
typeName += StrCat(" ", varName);
}
return typeName;
}
//-----------------------------------------------------------------------------
static bool IsTrivialStaticClassVarDecl(const DeclRefExpr& declRefExpr)
{
if(const VarDecl* VD = GetVarDeclFromDeclRefExpr(&declRefExpr)) {
return IsTrivialStaticClassVarDecl(*VD);
}
return false;
}
//-----------------------------------------------------------------------------
bool IsTrivialStaticClassVarDecl(const VarDecl& varDecl)
{
if(varDecl.isStaticLocal()) {
if(const auto* cxxRecordDecl = varDecl.getType()->getAsCXXRecordDecl()) {
if(cxxRecordDecl->hasNonTrivialDestructor()) {
return true;
}
}
}
return false;
}
//-----------------------------------------------------------------------------
std::string GetName(const DeclRefExpr& declRefExpr)
{
std::string name{};
const auto* declRefDecl = declRefExpr.getDecl();
const auto* declCtx = declRefDecl->getDeclContext();
const bool isFriend{(declRefDecl->getFriendObjectKind() != Decl::FOK_None)};
const bool hasNamespace{(declCtx && (declCtx->isNamespace() || declCtx->isInlineNamespace()) &&
!declCtx->isTransparentContext() && !isFriend)};
// get the namespace as well
if(hasNamespace) {
name = details::GetScope(declCtx);
} else if(declRefExpr.hasQualifier()) {
name = details::GetQualifiedName(*declRefDecl);
}
if(hasNamespace || !declRefExpr.hasQualifier()) {
std::string plainName{GetPlainName(declRefExpr)};
// try to handle the special case of a function local static with class type and non trivial destructor. In
// this case, as we teared that variable apart, we need to adjust the variable named and add a reinterpret
// cast
if(IsTrivialStaticClassVarDecl(declRefExpr)) {
if(const VarDecl* VD = GetVarDeclFromDeclRefExpr(&declRefExpr)) {
if(const auto* cxxRecordDecl = VD->getType()->getAsCXXRecordDecl()) {
plainName = StrCat(
"*reinterpret_cast<", GetName(*cxxRecordDecl), "*>(", BuildInternalVarName(plainName), ")");
}
}
}
name.append(plainName);
}
return name;
}
//-----------------------------------------------------------------------------
std::string GetNameAsFunctionPointer(const QualType& t)
{
std::string typeName{GetName(t)};
if(!t->isFunctionPointerType()) {
InsertBefore(typeName, "(", "(*)");
}
return typeName;
}
//-----------------------------------------------------------------------------
const char* GetNoExcept(const FunctionDecl& decl)
{
const auto* func = decl.getType()->castAs<FunctionProtoType>();
if(func && func->hasNoexceptExceptionSpec()) {
return kwSpaceNoexcept;
}
return "";
}
//-----------------------------------------------------------------------------
const char* GetConst(const CXXMethodDecl& decl)
{
if(decl.isConst()) {
return kwSpaceConst;
}
return "";
}
//-----------------------------------------------------------------------------
} // namespace clang::insights