-
-
Notifications
You must be signed in to change notification settings - Fork 243
/
InsightsHelpers.h
446 lines (360 loc) · 15.2 KB
/
InsightsHelpers.h
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
*
****************************************************************************/
#ifndef INSIGHTS_HELPERS_H
#define INSIGHTS_HELPERS_H
//-----------------------------------------------------------------------------
#include "clang/AST/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Lex/Lexer.h"
#include <functional>
#include <optional>
#include <string>
#include <variant>
#include "InsightsStrongTypes.h"
#include "StackList.h"
//-----------------------------------------------------------------------------
namespace clang::insights {
std::string BuildInternalVarName(const std::string_view& varName);
//-----------------------------------------------------------------------------
std::string MakeLineColumnName(const SourceManager& sm, const SourceLocation& loc, const std::string_view& prefix);
//-----------------------------------------------------------------------------
inline bool IsStaticStorageClass(const CXXMethodDecl* md)
{
return SC_Static == md->getStorageClass();
}
//-----------------------------------------------------------------------------
inline bool IsReferenceType(const ValueDecl* decl)
{
return decl and decl->getType()->isReferenceType();
}
//-----------------------------------------------------------------------------
inline bool IsReferenceType(const DeclRefExpr* decl)
{
return decl and IsReferenceType(decl->getDecl());
}
//-----------------------------------------------------------------------------
std::string BuildRetTypeName(const Decl& decl);
//-----------------------------------------------------------------------------
inline bool Contains(const std::string_view source, const std::string_view search)
{
return std::string::npos != source.find(search, 0);
}
//-----------------------------------------------------------------------------
template<typename K, typename V, typename U>
inline bool Contains(const llvm::DenseMap<K, V>& map, const U& key)
{
return map.find(key) != map.end();
}
//-----------------------------------------------------------------------------
void ReplaceAll(std::string& str, std::string_view from, std::string_view to);
//-----------------------------------------------------------------------------
void InsertBefore(std::string& source, const std::string_view& find, const std::string_view& replace);
//-----------------------------------------------------------------------------
inline const SourceManager& GetSM(const Decl& decl)
{
return decl.getASTContext().getSourceManager();
}
//-----------------------------------------------------------------------------
inline const LangOptions& GetLangOpts(const Decl& decl)
{
return decl.getASTContext().getLangOpts();
}
//-----------------------------------------------------------------------------
/// \brief Get the evaluated APValue from a `VarDecl`
///
/// Returns `nullptr` is the \c VarDecl is not evaluatable.
APValue* GetEvaluatedValue(const VarDecl& varDecl);
//-----------------------------------------------------------------------------
/// \brief Check whether a `VarDecl`s initialization can be done a compile-time.
///
/// This method checks, whether a \c VarDecl is initialized by a constant expression.
bool IsEvaluatable(const VarDecl& varDecl);
//-----------------------------------------------------------------------------
bool IsTrivialStaticClassVarDecl(const VarDecl& varDecl);
//-----------------------------------------------------------------------------
/*
* Get the name of a DeclRefExpr without the namespace
*/
std::string GetPlainName(const DeclRefExpr& DRE);
std::string GetName(const DeclRefExpr& declRefExpr);
std::string GetName(const VarDecl& VD);
//-----------------------------------------------------------------------------
STRONG_BOOL(QualifiedName);
std::string GetName(const NamedDecl& nd, const QualifiedName qualifiedName = QualifiedName::No);
//-----------------------------------------------------------------------------
std::string GetNameAsFunctionPointer(const QualType& t);
//-----------------------------------------------------------------------------
std::string GetLambdaName(const CXXRecordDecl& lambda);
inline std::string GetLambdaName(const LambdaExpr& lambda)
{
return GetLambdaName(*lambda.getLambdaClass());
}
//-----------------------------------------------------------------------------
std::string GetName(const CXXRecordDecl& RD);
//-----------------------------------------------------------------------------
std::string GetName(const CXXTemporaryObjectExpr& tmp);
//-----------------------------------------------------------------------------
std::string GetTemporaryName(const Expr& tmp);
//-----------------------------------------------------------------------------
/// \brief In Cfront mode we transform references to pointers
QualType GetType(QualType);
//-----------------------------------------------------------------------------
/// \brief Check whether this is an anonymous struct or union.
///
/// There is a dedicated function `isAnonymousStructOrUnion` which at this point no longer returns true. Hence this
/// method uses an empty record decl name as indication for an anonymous struct/union.
inline bool IsAnonymousStructOrUnion(const CXXRecordDecl* cxxRecordDecl)
{
if(cxxRecordDecl) {
return cxxRecordDecl->getName().empty();
}
return false;
}
//-----------------------------------------------------------------------------
void AppendTemplateTypeParamName(class OutputFormatHelper& ofm,
const TemplateTypeParmDecl* decl,
const bool isParameter,
const TemplateTypeParmType* type = nullptr);
//-----------------------------------------------------------------------------
/// \brief Remove decltype from a QualType, if possible.
const QualType GetDesugarType(const QualType& QT);
// -----------------------------------------------------------------------------
inline QualType GetDesugarReturnType(const FunctionDecl& FD)
{
return GetDesugarType(FD.getReturnType());
}
//-----------------------------------------------------------------------------
STRONG_BOOL(Unqualified);
std::string GetName(const QualType& t, const Unqualified unqualified = Unqualified::No);
//-----------------------------------------------------------------------------
std::string GetUnqualifiedScopelessName(const Type* type);
//-----------------------------------------------------------------------------
std::string
GetTypeNameAsParameter(const QualType& t, std::string_view varName, const Unqualified unqualified = Unqualified::No);
//-----------------------------------------------------------------------------
STRONG_BOOL(WithTemplateParameters);
STRONG_BOOL(IgnoreNamespace);
std::string GetNestedName(const NestedNameSpecifier* nns, const IgnoreNamespace ignoreNamespace = IgnoreNamespace::No);
std::string GetDeclContext(const DeclContext* ctx,
WithTemplateParameters withTemplateParameters = WithTemplateParameters::No);
//-----------------------------------------------------------------------------
const std::string EvaluateAsFloat(const FloatingLiteral& expr);
const std::string GetNoExcept(const FunctionDecl& decl);
const std::string_view GetConst(const FunctionDecl& decl);
//-----------------------------------------------------------------------------
std::string GetElaboratedTypeKeyword(const ElaboratedTypeKeyword keyword);
//-----------------------------------------------------------------------------
uint64_t GetSize(const ConstantArrayType*);
//-----------------------------------------------------------------------------
template<typename QT, typename SUB_T>
static bool TypeContainsSubType(const QualType& t)
{
if(const auto* lref = dyn_cast_or_null<QT>(t.getTypePtrOrNull())) {
const auto subType = GetDesugarType(lref->getPointeeType());
const auto& ct = subType.getCanonicalType();
const auto* plainSubType = ct.getTypePtrOrNull();
return isa<SUB_T>(plainSubType);
}
return false;
}
//-----------------------------------------------------------------------------
template<typename T, typename TFunc>
void for_each(T start, T end, TFunc&& func)
{
for(; start < end; ++start) {
func(start);
}
}
//-----------------------------------------------------------------------------
/// \brief Track the scope we are currently in to build a properly scoped variable.
///
/// The AST only knows about absolute scopes (namespace, struct, class), as once a declaration is parsed it is either in
/// a scope or not. Each request to give me the namespace automatically leads to the entire scope the item is in. This
/// makes it hard to have constructs like this: \code struct One
/// {
/// static const int o{};
///
/// struct Two
/// {
/// static const int d = o;
/// };
///
/// static const int a = Two::d;
///};
/// \endcode
///
/// Here the initializer of \c a is in the scope \c One::Two::d. At this point the qualification \c Two::d is enought.
///
/// \c ScopeHelper tracks whether we are currently in a class or namespace and simply remove the path we already in from
/// the scope.
struct ScopeHelper : public StackListEntry<ScopeHelper>
{
ScopeHelper(const size_t len)
: mLength{len}
{
}
const size_t mLength; //!< Length of the scope as it was _before_ this declaration was appended.
};
//-----------------------------------------------------------------------------
/// \brief The ScopeHandler tracks the current scope.
///
/// The \c ScopeHandler tracks the current scope, knows about all the parts and is able to remove the current scope part
/// from a name.
class ScopeHandler
{
public:
ScopeHandler(const Decl* d);
~ScopeHandler();
/// \brief Remove the current scope from a string.
///
/// The default is that the entire scope is replaced. Suppose we are
/// currently in N::X and having a symbol N::X::y then N::X:: is removed. However, there is a special case, where
/// the last item is skipped.
static std::string RemoveCurrentScope(std::string name);
private:
using ScopeStackType = StackList<ScopeHelper>;
ScopeStackType& mStack; //!< Access to the global \c ScopeHelper stack.
ScopeHelper mHelper; //!< The \c ScopeHelper this item refers to.
static inline ScopeStackType mGlobalStack; //!< Global stack to keep track of the scope elements.
static inline std::string mScope; //!< The entire scope we are already in.
};
//-----------------------------------------------------------------------------
/// \brief Helper to create a \c ScopeHandler on the stack which adds the current \c Decl to it and removes it once the
/// scope is left.
#define SCOPE_HELPER(d) \
ScopeHandler _scopeHandler \
{ \
d \
}
//-----------------------------------------------------------------------------
/// \brief Specialization for \c ::llvm::raw_string_ostream with an internal \c std::string buffer.
class StringStream : public ::llvm::raw_string_ostream
{
private:
std::string mData{};
public:
StringStream()
: ::llvm::raw_string_ostream{mData}
{
}
void Print(const TemplateArgument&);
void Print(const TemplateSpecializationType&);
void Print(const TypeConstraint&);
void Print(const StringLiteral&);
void Print(const CharacterLiteral&);
};
//-----------------------------------------------------------------------------
/// \brief A helper which invokes a lambda when the scope is destroyed.
template<typename T>
class FinalAction
{
public:
explicit FinalAction(T&& action)
: mAction{std::forward<T>(action)}
{
}
~FinalAction() { mAction(); }
private:
T mAction;
};
//-----------------------------------------------------------------------------
/// \brief Handy helper to avoid longish comparisons.
///
/// The idea is taken from a talk from Björn Fahller at NDC TechTown 2019: Modern Techniques for Keeping Your Code DRY
/// (https://youtu.be/YUWuNpxZa5k)
/// \code
/// if( is{v}.any_of(A, B, C) ) { ... }
/// \endcode
template<typename T>
struct is
{
T t;
constexpr bool any_of(const auto&... ts) const { return ((t == ts) or ...); }
};
//-----------------------------------------------------------------------------
template<typename T>
is(T) -> is<T>;
//-----------------------------------------------------------------------------
/// Go deep in a Stmt if necessary and look to all childs for a DeclRefExpr.
const DeclRefExpr* FindDeclRef(const Stmt* stmt);
//-----------------------------------------------------------------------------
///! Find a LambdaExpr inside a Decltype
class P0315Visitor : public RecursiveASTVisitor<P0315Visitor>
{
std::variant<std::reference_wrapper<class OutputFormatHelper>, std::reference_wrapper<class CodeGenerator>>
mConsumer;
const LambdaExpr* mLambdaExpr{};
public:
P0315Visitor(class OutputFormatHelper& ofm)
: mConsumer{ofm}
{
}
P0315Visitor(class CodeGenerator& cg)
: mConsumer{cg}
{
}
bool VisitLambdaExpr(const LambdaExpr* expr);
const LambdaExpr* Get() const { return mLambdaExpr; }
};
//-----------------------------------------------------------------------------
template<typename T, typename U>
struct BackupAndRestore
{
T& mValue;
T mBackup{};
BackupAndRestore(T& value, U&& newVal)
: mValue(value)
, mBackup{mValue}
{
mValue = std::forward<U>(newVal);
}
~BackupAndRestore() { mValue = mBackup; }
};
//-----------------------------------------------------------------------------
template<class T>
class MyOptional : public std::optional<T>
{
public:
using std::optional<T>::optional;
template<class Return>
MyOptional<Return> and_then(std::function<MyOptional<Return>(T)> func)
requires(not std::is_pointer_v<T>)
{
if(not this->has_value()) {
return {};
}
return func(this->value());
}
template<class Return>
MyOptional<Return> and_then(std::function<MyOptional<Return>(std::remove_pointer_t<T>&)> func)
requires(std::is_pointer_v<T>)
{
if(not this->has_value()) {
return {};
}
if(this->value() == nullptr) {
return {};
} else {
return func(*this->value());
}
}
template<class Return>
MyOptional<Return> and_not(std::function<MyOptional<Return>(T)> func)
{
if(not this->has_value()) {
return {};
}
if(not func(this->value()).has_value()) {
return *this;
}
return {};
}
};
//-----------------------------------------------------------------------------
} // namespace clang::insights
#endif /* INSIGHTS_HELPERS_H */