-
-
Notifications
You must be signed in to change notification settings - Fork 245
/
InsightsHelpers.cpp
1623 lines (1293 loc) · 57 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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
*
* C++ Insights, copyright (C) by Andreas Fertig
* Distributed under an MIT license. See LICENSE for details
*
****************************************************************************/
#include "InsightsHelpers.h"
#include "ASTHelpers.h"
#include "ClangCompat.h"
#include "CodeGenerator.h"
#include "DPrint.h"
#include "Insights.h"
#include "InsightsStaticStrings.h"
#include "OutputFormatHelper.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Sema/Lookup.h"
//-----------------------------------------------------------------------------
namespace clang::insights {
ScopeHandler::ScopeHandler(const Decl* d)
: mStack{mGlobalStack}
, mHelper{mScope.length()}
{
mStack.push(mHelper);
if(const auto* recordDecl = dyn_cast_or_null<CXXRecordDecl>(d)) {
mScope.append(GetName(*recordDecl));
if(const auto* classTmplSpec = dyn_cast_or_null<ClassTemplateSpecializationDecl>(recordDecl)) {
OutputFormatHelper ofm{};
CodeGenerator codeGenerator{ofm};
codeGenerator.InsertTemplateArgs(*classTmplSpec);
mScope.append(ofm);
}
} else if(const auto* namespaceDecl = dyn_cast_or_null<NamespaceDecl>(d)) {
mScope.append(namespaceDecl->getName());
}
if(not mScope.empty()) {
mScope.append("::");
}
}
//-----------------------------------------------------------------------------
ScopeHandler::~ScopeHandler()
{
const auto length = mStack.pop()->mLength;
mScope.resize(length);
}
//-----------------------------------------------------------------------------
std::string ScopeHandler::RemoveCurrentScope(std::string name)
{
if(mScope.length()) {
auto findAndReplace = [&name](const std::string& scope) {
if(const auto startPos = name.find(scope, 0); std::string::npos != startPos) {
if(const auto pos = startPos + scope.length();
(pos > name.length()) or (name[pos] != '*')) { // keep member points (See #374)
name.replace(startPos, scope.length(), ""sv);
return true;
}
}
return false;
};
// The default is that we can replace the entire scope. Suppose we are currently in N::X and having a symbol
// N::X::y then N::X:: is removed.
if(not findAndReplace(mScope)) {
// A special case where we need to remove the scope without the last item.
std::string tmp{mScope};
tmp.resize(mGlobalStack.back().mLength);
findAndReplace(tmp);
}
}
return name;
}
//-----------------------------------------------------------------------------
static std::string GetNamePlain(const NamedDecl& decl)
{
if(const auto* fd = dyn_cast_or_null<FunctionDecl>(&decl); fd and GetInsightsOptions().UseShow2C) {
if(fd->isOverloadedOperator()) {
switch(fd->getOverloadedOperator()) {
#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
case OO_##Name: return "operator" #Name;
#include "clang/Basic/OperatorKinds.def"
#undef OVERLOADED_OPERATOR
default: break;
}
}
}
return decl.getDeclName().getAsString();
}
std::string GetPlainName(const DeclRefExpr& DRE)
{
return ScopeHandler::RemoveCurrentScope(GetNamePlain(*DRE.getDecl()));
}
//-----------------------------------------------------------------------------
STRONG_BOOL(InsightsSuppressScope);
//-----------------------------------------------------------------------------
STRONG_BOOL(InsightsCanonicalTypes);
//-----------------------------------------------------------------------------
static std::string GetUnqualifiedScopelessName(const Type* type, const InsightsSuppressScope supressScope);
//-----------------------------------------------------------------------------
struct CppInsightsPrintingPolicy : PrintingPolicy
{
unsigned CppInsightsUnqualified : 1; // NOLINT
InsightsSuppressScope CppInsightsSuppressScope; // NOLINT
CppInsightsPrintingPolicy(const Unqualified unqualified,
const InsightsSuppressScope supressScope,
const InsightsCanonicalTypes insightsCanonicalTypes = InsightsCanonicalTypes::No)
: PrintingPolicy{LangOptions{}}
{
adjustForCPlusPlus();
SuppressUnwrittenScope = true;
Alignof = true;
ConstantsAsWritten = true;
AnonymousTagLocations = false; // does remove filename and line for from lambdas in parameters
PrintCanonicalTypes = InsightsCanonicalTypes::Yes == insightsCanonicalTypes;
CppInsightsUnqualified = (Unqualified::Yes == unqualified);
CppInsightsSuppressScope = supressScope;
}
CppInsightsPrintingPolicy()
: CppInsightsPrintingPolicy{Unqualified::No, InsightsSuppressScope::No}
{
}
};
//-----------------------------------------------------------------------------
void ReplaceAll(std::string& str, std::string_view from, std::string_view to)
{
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
}
}
//-----------------------------------------------------------------------------
namespace details {
static void
BuildNamespace(std::string& fullNamespace, const NestedNameSpecifier* stmt, const IgnoreNamespace ignoreNamespace)
{
RETURN_IF(not stmt);
if(const auto* prefix = stmt->getPrefix();
prefix and not((NestedNameSpecifier::TypeSpecWithTemplate == stmt->getKind()) and
isa<DependentTemplateSpecializationType>(stmt->getAsType()))) {
BuildNamespace(fullNamespace, prefix, ignoreNamespace);
}
switch(stmt->getKind()) {
case NestedNameSpecifier::Identifier: fullNamespace.append(stmt->getAsIdentifier()->getName()); break;
case NestedNameSpecifier::Namespace:
RETURN_IF((IgnoreNamespace::Yes == ignoreNamespace) or (stmt->getAsNamespace()->isAnonymousNamespace()));
fullNamespace.append(stmt->getAsNamespace()->getName());
break;
case NestedNameSpecifier::NamespaceAlias: fullNamespace.append(stmt->getAsNamespaceAlias()->getName()); break;
case NestedNameSpecifier::TypeSpecWithTemplate:
if(auto* dependentSpecType = stmt->getAsType()->getAs<DependentTemplateSpecializationType>()) {
fullNamespace.append(GetElaboratedTypeKeyword(dependentSpecType->getKeyword()));
}
[[fallthrough]];
case NestedNameSpecifier::TypeSpec:
fullNamespace.append(GetUnqualifiedScopelessName(stmt->getAsType(), InsightsSuppressScope::Yes));
// The template parameters are already contained in the type we inserted above.
break;
default: break;
}
fullNamespace.append("::"sv);
}
//-----------------------------------------------------------------------------
} // namespace details
std::string GetNestedName(const NestedNameSpecifier* nns, const IgnoreNamespace ignoreNamespace)
{
std::string ret{};
if(nns) {
details::BuildNamespace(ret, nns, ignoreNamespace);
}
return ret;
}
//-----------------------------------------------------------------------------
static const std::string GetAsCPPStyleString(const QualType& t, const CppInsightsPrintingPolicy& printingPolicy)
{
return t.getAsString(printingPolicy);
}
//-----------------------------------------------------------------------------
std::string BuildInternalVarName(const std::string_view& varName)
{
return StrCat("__", varName);
}
//-----------------------------------------------------------------------------
static std::string
BuildInternalVarName(const std::string_view& varName, const SourceLocation& loc, const SourceManager& sm)
{
const auto lineNo = sm.getSpellingLineNumber(loc);
return StrCat(BuildInternalVarName(varName), lineNo);
}
//-----------------------------------------------------------------------------
void InsertBefore(std::string& source, const std::string_view& find, const std::string_view& 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_view& find, const std::string_view& replace)
{
const std::string::size_type i = source.find(find, 0);
if(std::string::npos != i) {
source.insert(i + find.length(), replace);
}
}
//-----------------------------------------------------------------------------
std::string MakeLineColumnName(const SourceManager& sm, const SourceLocation& loc, const std::string_view& prefix)
{
// In case of a macro expansion the expansion(line/column) number gives a unique value.
const auto lineNo = loc.isMacroID() ? sm.getExpansionLineNumber(loc) : sm.getSpellingLineNumber(loc);
const auto columnNo = loc.isMacroID() ? sm.getExpansionColumnNumber(loc) : sm.getSpellingColumnNumber(loc);
return StrCat(prefix, lineNo, "_"sv, columnNo);
}
//-----------------------------------------------------------------------------
static std::string MakeLineColumnName(const Decl& decl, const std::string_view prefix)
{
return MakeLineColumnName(GetSM(decl), decl.getBeginLoc(), prefix);
}
//-----------------------------------------------------------------------------
std::string GetLambdaName(const CXXRecordDecl& lambda)
{
static constexpr auto lambdaPrefix{"__lambda_"sv};
return MakeLineColumnName(lambda, lambdaPrefix);
}
//-----------------------------------------------------------------------------
static std::string GetAnonymStructOrUnionName(const CXXRecordDecl& cxxRecordDecl)
{
static constexpr auto prefix{"__anon_"sv};
return MakeLineColumnName(cxxRecordDecl, prefix);
}
//-----------------------------------------------------------------------------
std::string BuildRetTypeName(const Decl& decl)
{
static constexpr auto retTypePrefix{"retType_"sv};
return MakeLineColumnName(decl, retTypePrefix);
}
//-----------------------------------------------------------------------------
const QualType GetDesugarType(const QualType& QT)
{
if(QT.getTypePtrOrNull()) {
if(const auto* autoType = QT->getAs<clang::AutoType>(); autoType and autoType->isSugared()) {
const auto dt = autoType->getDeducedType();
if(const auto* et = dt->getAs<ElaboratedType>()) {
return et->getNamedType();
} else {
return dt;
}
} else 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"sv);
}
return std::string{str.str()};
}
//-----------------------------------------------------------------------------
static const VarDecl* GetVarDeclFromDeclRefExpr(const DeclRefExpr& declRefExpr)
{
const auto* valueDecl = declRefExpr.getDecl();
return dyn_cast_or_null<VarDecl>(valueDecl);
}
//-----------------------------------------------------------------------------
// own implementation due to lambdas
std::string GetDeclContext(const DeclContext* ctx, WithTemplateParameters withTemplateParameters)
{
OutputFormatHelper mOutputFormatHelper{};
SmallVector<const DeclContext*, 8> contexts{};
while(ctx) {
if(isa<NamedDecl>(ctx)) {
contexts.push_back(ctx);
}
ctx = ctx->getParent();
}
for(const auto* declContext : llvm::reverse(contexts)) {
if(const auto* classTmplSpec = dyn_cast<ClassTemplateSpecializationDecl>(declContext)) {
mOutputFormatHelper.Append(classTmplSpec->getName());
CodeGenerator codeGenerator{mOutputFormatHelper};
codeGenerator.InsertTemplateArgs(*classTmplSpec);
} else if(const auto* nd = dyn_cast<NamespaceDecl>(declContext)) {
if(nd->isAnonymousNamespace() or nd->isInline()) {
continue;
}
mOutputFormatHelper.Append(nd->getName());
} else if(const auto* rd = dyn_cast<RecordDecl>(declContext)) {
if(not rd->getIdentifier()) {
continue;
}
mOutputFormatHelper.Append(rd->getName());
// A special case at least for out-of-line static member variables of a class template. They need to carry
// the template parameters of the class template.
if(WithTemplateParameters::Yes == withTemplateParameters /*declContext->isNamespace() or declContext->getLexicalParent()->isNamespace() or declContext->getLexicalParent()->isTranslationUnit()*/) {
if(const auto* cxxRecordDecl = dyn_cast_or_null<CXXRecordDecl>(rd)) {
if(const auto* classTmpl = cxxRecordDecl->getDescribedClassTemplate()) {
CodeGenerator codeGenerator{mOutputFormatHelper};
codeGenerator.InsertTemplateParameters(*classTmpl->getTemplateParameters(),
CodeGenerator::TemplateParamsOnly::Yes);
}
}
}
} else if(dyn_cast<FunctionDecl>(declContext)) {
continue;
} else if(const auto* ed = dyn_cast<EnumDecl>(declContext)) {
if(not ed->isScoped()) {
continue;
}
mOutputFormatHelper.Append(ed->getName());
} else {
mOutputFormatHelper.Append(cast<NamedDecl>(declContext)->getName());
}
mOutputFormatHelper.Append("::"sv);
}
return mOutputFormatHelper.GetString();
}
//-----------------------------------------------------------------------------
namespace details {
STRONG_BOOL(RemoveCurrentScope); ///!< In some cases we need to keep the scope for a while, so don't remove the scope
/// we are in right now.
//-----------------------------------------------------------------------------
static std::string GetQualifiedName(const NamedDecl& decl,
const RemoveCurrentScope removeCurrentScope = RemoveCurrentScope::Yes)
{
std::string scope{GetDeclContext(decl.getDeclContext())};
scope += decl.getName();
if(RemoveCurrentScope::Yes == removeCurrentScope) {
return ScopeHandler::RemoveCurrentScope(scope);
}
return scope;
}
//-----------------------------------------------------------------------------
static std::string GetScope(const DeclContext* declCtx,
const RemoveCurrentScope removeCurrentScope = RemoveCurrentScope::Yes)
{
std::string name{};
if(not declCtx->isTranslationUnit() and not declCtx->isFunctionOrMethod()) {
while(declCtx->isInlineNamespace()) {
declCtx = declCtx->getParent();
}
if(not declCtx->isTranslationUnit() and (declCtx->isNamespace() or declCtx->getParent()->isTranslationUnit())) {
if(const auto* namedDecl = dyn_cast_or_null<NamedDecl>(declCtx)) {
name = GetQualifiedName(*namedDecl, removeCurrentScope);
name.append("::"sv);
}
}
}
return name;
}
//-----------------------------------------------------------------------------
/// \brief SimpleTypePrinter a partially substitution of Clang's TypePrinter.
///
/// With Clang 9 there seems to be a change in `lib/AST/TypePrinter.cpp` in `printTemplateTypeParmBefore`. It now
/// inserts `auto` when it is a lambda auto parameter. Which is correct, but C++ Insights needs the
/// template parameter name to make up compiling code. Hence, this `if` "overrides" the implementation of
/// TypePrinter in that case.
///
/// It also drops some former code which handled `ClassTemplateSpecializationDecl` in a special way. Here the template
/// parameters can be lambdas. Those they need a proper name.
class SimpleTypePrinter
{
private:
const QualType& mType;
const CppInsightsPrintingPolicy& mPrintingPolicy;
OutputFormatHelper mData{};
std::string mDataAfter{};
bool mHasData{false};
bool mSkipSpace{false};
bool mScanningArrayDimension{}; //!< Only the outer most ConstantArrayType handles the array dimensions and size
std::string mScope{}; //!< A scope coming from an ElaboratedType which is used for a
//!< ClassTemplateSpecializationDecl if there is no other scope
bool HandleType(const TemplateTypeParmType* type)
{
const TemplateTypeParmDecl* decl = type->getDecl();
if((nullptr == type->getIdentifier()) or
(decl and decl->isImplicit()) /* this fixes auto operator()(type_parameter_0_0 container) const */) {
AppendTemplateTypeParamName(mData, decl, true, type);
return true;
}
return false;
}
bool HandleType(const LValueReferenceType* type)
{
mDataAfter += " &"sv;
return HandleType(type->getPointeeType().getTypePtrOrNull());
}
bool HandleType(const RValueReferenceType* type)
{
mDataAfter += " &&"sv;
return HandleType(type->getPointeeType().getTypePtrOrNull());
}
bool HandleType(const PointerType* type)
{
mDataAfter += " *"sv;
return HandleType(type->getPointeeType().getTypePtrOrNull());
}
bool HandleType(const InjectedClassNameType* type) { return HandleType(type->getInjectedTST()); }
bool HandleType(const RecordType* type)
{
/// In case one of the template parameters is a lambda we need to insert the made up name.
if(const auto* tt = dyn_cast_or_null<ClassTemplateSpecializationDecl>(type->getDecl())) {
if(const auto* identifierName = mType.getBaseTypeIdentifier()) {
const auto& scope = GetScope(type->getDecl()->getDeclContext());
// If we don't have a scope with GetScope use a possible one from ElaboratedType
if((InsightsSuppressScope::Yes == mPrintingPolicy.CppInsightsSuppressScope) or scope.empty()) {
mData.Append(mScope);
} else {
mData.Append(scope);
}
mData.Append(identifierName->getName());
CodeGenerator codeGenerator{mData};
codeGenerator.InsertTemplateArgs(*tt);
return true;
}
} else if(const auto* cxxRecordDecl = type->getAsCXXRecordDecl()) {
// Special handling for dependent types. For example, ClassOperatorHandler7Test.cpp A<...* >::B.
if(type->isDependentType()) {
std::string context{GetDeclContext(type->getDecl()->getDeclContext())};
if(not context.empty()) {
mData.Append(std::move(context));
mData.Append(cxxRecordDecl->getName());
return true;
}
}
if(cxxRecordDecl->isLambda()) {
mData.Append(GetLambdaName(*cxxRecordDecl));
return true;
}
// Handle anonymous struct or union.
if(IsAnonymousStructOrUnion(cxxRecordDecl)) {
mData.Append(GetAnonymStructOrUnionName(*cxxRecordDecl));
return true;
}
// we need a name here, as DecltypeType always says true
mData.Append(GetName(*cxxRecordDecl));
}
return false;
}
bool HandleType(const AutoType* type) { return HandleType(type->getDeducedType().getTypePtrOrNull()); }
bool HandleType(const SubstTemplateTypeParmType* type)
{
return HandleType(type->getReplacementType().getTypePtrOrNull());
}
bool HandleType(const ElaboratedType* type)
{
const IgnoreNamespace ignoreNamespace = (mPrintingPolicy.CppInsightsSuppressScope == InsightsSuppressScope::Yes)
? IgnoreNamespace::No
: IgnoreNamespace::Yes;
mScope = GetNestedName(type->getQualifier(), ignoreNamespace);
const bool ret = HandleType(type->getNamedType().getTypePtrOrNull());
mScope.clear();
return ret;
}
bool HandleType(const DependentTemplateSpecializationType* type)
{
mData.Append(GetElaboratedTypeKeyword(type->getKeyword()),
GetNestedName(type->getQualifier()),
kwTemplateSpace,
type->getIdentifier()->getName());
CodeGenerator codeGenerator{mData};
codeGenerator.InsertTemplateArgs(*type);
return true;
}
bool HandleType(const DeducedTemplateSpecializationType* type)
{
return HandleType(type->getDeducedType().getTypePtrOrNull());
}
bool HandleType(const TemplateSpecializationType* type)
{
if(type->getAsRecordDecl()) {
// Only if it was some sort of "used" `RecordType` we continue here.
if(HandleType(type->getAsRecordDecl()->getTypeForDecl())) {
HandleType(type->getPointeeType().getTypePtrOrNull());
return true;
}
}
/// This is a specialty discovered with #188_2. In some cases there is a `TemplateTypeParmDecl` which has no
/// identifier name. Then it will end up as `type-parameter-...`. At least in #188_2: _Head_base<_Idx,
/// type_parameter_0_1, true> the repetition of the template specialization arguments is not required.
/// `hasNoName` tries to detect this case and does then print the name of the template only.
const bool hasNoName{[&] {
for(const auto& arg : type->template_arguments()) {
StringStream sstream{};
sstream.Print(arg);
if(Contains(sstream.str(), "type-parameter"sv)) {
return true;
}
}
return false;
}()};
if(hasNoName) {
StringStream sstream{};
sstream.Print(*type);
mData.Append(sstream.str());
return true;
}
return false;
}
bool HandleType(const MemberPointerType* type)
{
HandleType(type->getPointeeType().getTypePtrOrNull());
mData.Append('(');
const bool ret = HandleType(type->getClass());
mData.Append("::*)"sv);
HandleTypeAfter(type->getPointeeType().getTypePtrOrNull());
return ret;
}
bool HandleType(const FunctionProtoType* type) { return HandleType(type->getReturnType().getTypePtrOrNull()); }
void HandleTypeAfter(const FunctionProtoType* type)
{
mData.Append('(');
mSkipSpace = true;
for(OnceFalse needsComma{}; const auto& t : type->getParamTypes()) {
if(needsComma) {
mData.Append(", "sv);
}
HandleType(t.getTypePtrOrNull());
}
mSkipSpace = false;
mData.Append(')');
if(not type->getMethodQuals().empty()) {
mData.Append(" "sv, type->getMethodQuals().getAsString());
}
/// Currently, we are skipping `T->getRefQualifier()` and the exception specification, as well as the trailing
/// return type.
}
bool HandleType(const BuiltinType* type)
{
mData.Append(type->getName(mPrintingPolicy));
if(not mSkipSpace) {
mData.Append(' ');
}
return false;
}
bool HandleType(const TypedefType* type)
{
if(const auto* decl = type->getDecl()) {
/// Another filter place for type-parameter where it is contained in the FQN but leads to none compiling
/// code. Remove it to keep the code valid.
if(Contains(decl->getQualifiedNameAsString(), "type-parameter"sv)) {
auto* identifierInfo = decl->getIdentifier();
mData.Append(identifierInfo->getName());
return true;
}
return HandleType(decl->getUnderlyingType().getTypePtrOrNull());
}
return HandleType(type->getPointeeType().getTypePtrOrNull());
}
bool HandleType(const ConstantArrayType* type)
{
// Only the outer most ConstantArrayType generates the aary dimensions, block others.
bool scanningArrayDimension = false;
if(not mScanningArrayDimension) {
mScanningArrayDimension = true;
scanningArrayDimension = true;
}
const bool ret = HandleType(type->getElementType().getTypePtrOrNull());
// Handle the array dimension after the type has been parsed.
if(scanningArrayDimension) {
do {
mData.Append("["sv, GetSize(type), "]"sv);
} while((type = dyn_cast_or_null<ConstantArrayType>(type->getElementType().getTypePtrOrNull())));
mScanningArrayDimension = false;
}
return ret;
}
bool HandleType(const PackExpansionType* type)
{
const bool ret = HandleType(type->getPattern().getTypePtrOrNull());
if(ret) {
mData.Append(kwElipsis);
}
return ret;
}
bool HandleType(const DecltypeType* type)
{
// A DecltypeType in a template definition is unevaluated and refers ti itself. This check ensures, that in such
// a situation no expansion is performed.
if(not isa_and_nonnull<DecltypeType>(type->desugar().getTypePtrOrNull())) {
const bool skipSpace{mSkipSpace};
mSkipSpace = true;
HandleType(type->desugar().getTypePtrOrNull());
mSkipSpace = skipSpace;
// if we hit a DecltypeType always use the expanded version to support things like a DecltypeType wrapped in
// an LValueReferenceType
return true;
}
if(not isa_and_nonnull<DeclRefExpr>(type->getUnderlyingExpr())) {
P0315Visitor visitor{mData};
return not visitor.TraverseStmt(type->getUnderlyingExpr());
}
return false;
}
bool HandleType(const Type* type)
{
#define HANDLE_TYPE(t) \
if(isa<t>(type)) { \
return HandleType(dyn_cast_or_null<t>(type)); \
}
if(nullptr == type) {
return false;
}
HANDLE_TYPE(FunctionProtoType);
HANDLE_TYPE(PointerType);
HANDLE_TYPE(LValueReferenceType);
HANDLE_TYPE(RValueReferenceType);
HANDLE_TYPE(TemplateTypeParmType);
HANDLE_TYPE(RecordType);
HANDLE_TYPE(AutoType);
HANDLE_TYPE(SubstTemplateTypeParmType);
HANDLE_TYPE(ElaboratedType);
HANDLE_TYPE(TemplateSpecializationType);
HANDLE_TYPE(DeducedTemplateSpecializationType);
HANDLE_TYPE(MemberPointerType);
HANDLE_TYPE(BuiltinType);
HANDLE_TYPE(TypedefType);
HANDLE_TYPE(ConstantArrayType);
HANDLE_TYPE(InjectedClassNameType);
HANDLE_TYPE(DependentTemplateSpecializationType);
HANDLE_TYPE(PackExpansionType);
HANDLE_TYPE(DecltypeType);
#undef HANDLE_TYPE
return false;
}
void HandleTypeAfter(const Type* type)
{
#define HANDLE_TYPE(t) \
if(isa<t>(type)) { \
HandleTypeAfter(dyn_cast_or_null<t>(type)); \
}
if(nullptr != type) {
HANDLE_TYPE(FunctionProtoType);
}
}
void AddCVQualifiers(const Qualifiers& quals)
{
if((false == mPrintingPolicy.CppInsightsUnqualified) and not quals.empty()) {
mData.Append(quals.getAsString());
if(not mData.empty() and not mSkipSpace) {
mData.Append(' ');
}
}
}
public:
SimpleTypePrinter(const QualType& qt, const CppInsightsPrintingPolicy& printingPolicy)
: mType{qt}
, mPrintingPolicy{printingPolicy}
{
}
std::string& GetString() { return mData.GetString(); }
bool GetTypeString()
{
if(const SplitQualType splitted{mType.split()}; splitted.Quals.empty()) {
const auto& canonicalType = mType.getCanonicalType();
if(canonicalType->getPointeeType().getLocalFastQualifiers()) {
AddCVQualifiers(canonicalType->getPointeeType().getLocalQualifiers());
} else if(canonicalType.getLocalFastQualifiers()) {
AddCVQualifiers(canonicalType.getLocalQualifiers());
}
} else {
AddCVQualifiers(splitted.Quals);
}
const auto* typePtr = mType.getTypePtrOrNull();
mHasData = HandleType(typePtr);
mData.Append(mDataAfter);
// Take care of 'char* const'
if(mType.getQualifiers().hasFastQualifiers()) {
const QualType fastQualifierType{typePtr, mType.getQualifiers().getFastQualifiers()};
mSkipSpace = true;
AddCVQualifiers(fastQualifierType.getCanonicalType()->getPointeeType().getLocalQualifiers());
}
return mHasData;
}
};
//-----------------------------------------------------------------------------
static std::string GetName(QualType t,
const Unqualified unqualified = Unqualified::No,
const InsightsSuppressScope supressScope = InsightsSuppressScope::No)
{
const CppInsightsPrintingPolicy printingPolicy{unqualified,
supressScope,
(isa<AutoType>(t.getTypePtrOrNull())) ? InsightsCanonicalTypes::Yes
: InsightsCanonicalTypes::No};
QualType tt = t;
if(const auto* et = tt->getAs<ElaboratedType>()) {
if((nullptr == et->getQualifier()) and (nullptr == et->getOwnedTagDecl())) {
const auto quals = tt.getLocalFastQualifiers();
tt = et->getNamedType();
tt.setLocalFastQualifiers(quals);
}
}
if(SimpleTypePrinter st{t, printingPolicy}; st.GetTypeString()) {
return ScopeHandler::RemoveCurrentScope(st.GetString());
} else if(true == printingPolicy.CppInsightsUnqualified) {
return ScopeHandler::RemoveCurrentScope(GetAsCPPStyleString(tt.getUnqualifiedType(), printingPolicy));
}
return ScopeHandler::RemoveCurrentScope(GetAsCPPStyleString(tt, printingPolicy));
}
} // namespace details
//-----------------------------------------------------------------------------
static bool HasOverload(const FunctionDecl* fd)
{
auto* ncfd = const_cast<FunctionDecl*>(fd);
Sema& sema = GetGlobalCI().getSema();
LookupResult result{sema, ncfd->getDeclName(), {}, Sema::LookupOrdinaryName};
if(sema.LookupName(result, sema.getScopeForContext(ncfd->getDeclContext()))) {
return LookupResult::FoundOverloaded == result.getResultKind();
}
return false;
}
//-----------------------------------------------------------------------------
std::string GetSpecialMemberName(const ValueDecl* vd);
//-----------------------------------------------------------------------------
std::string GetCfrontOverloadedFunctionName(const FunctionDecl* fd)
{
std::string name{};
if(fd and GetInsightsOptions().UseShow2C and HasOverload(fd) and not fd->isMain()) {
name = GetSpecialMemberName(fd);
if(not fd->param_empty()) {
name += "_";
for(const auto& param : fd->parameters()) {
QualType t = param->getType();
QualType plainType = t.getNonReferenceType();
plainType.removeLocalConst();
plainType.removeLocalVolatile();
std::string ptr{};
while(plainType->isPointerType()) {
ptr += "p";
plainType = plainType->getPointeeType();
auto quals = plainType.getQualifiers();
auto lquals = plainType.getLocalQualifiers();
if(quals.hasConst() or lquals.hasConst()) {
ptr += "c";
}
plainType.removeLocalConst();
}
if(t.isCanonical()) {
t = t.getCanonicalType();
}
if(plainType->isBuiltinType() and plainType->hasUnsignedIntegerRepresentation()) {
std::string tmp{GetName(plainType)};
ReplaceAll(tmp, "unsigned ", "u");
name += tmp;
} else {
name += GetName(plainType);
}
auto quals = t.getQualifiers();
auto lquals = t.getLocalQualifiers();
if(t->isPointerType()) {
name += ptr;
}
if(quals.hasConst() or lquals.hasConst()) {
name += "c";
}
if(t->isLValueReferenceType()) {
name += "r";
}
if(t->isRValueReferenceType()) {
name += "R";
}
}
}
} else if(const auto* md = dyn_cast_or_null<CXXMethodDecl>(fd);
md and GetInsightsOptions().UseShow2C and md->isVirtual()) {
name = GetName(*md->getParent());
}
return name;
}
//-----------------------------------------------------------------------------
STRONG_BOOL(UseLexicalParent);
//-----------------------------------------------------------------------------
static bool NeedsNamespace(const Decl& decl, UseLexicalParent useLexicalParent)
{
const auto* declCtx = decl.getDeclContext();
if(UseLexicalParent::Yes == useLexicalParent) {
declCtx = declCtx->getLexicalParent();
}
if(nullptr == declCtx) {