forked from andreasfertig/cppinsights
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CodeGenerator.cpp
5143 lines (4101 loc) · 187 KB
/
CodeGenerator.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 <algorithm>
#include <optional>
#include <vector>
#include "ASTHelpers.h"
#include "ClangCompat.h"
#include "CodeGenerator.h"
#include "DPrint.h"
#include "Insights.h"
#include "InsightsHelpers.h"
#include "InsightsOnce.h"
#include "InsightsStrCat.h"
#include "NumberIterator.h"
#include "clang/AST/RecordLayout.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Sema/Sema.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Path.h"
//-----------------------------------------------------------------------------
/// \brief Convenience macro to create a \ref LambdaScopeHandler on the stack.
#define LAMBDA_SCOPE_HELPER(type) \
LambdaScopeHandler lambdaScopeHandler{mLambdaStack, mOutputFormatHelper, LambdaCallerType::type};
//-----------------------------------------------------------------------------
/// \brief The lambda scope helper is only created if cond is true
#define CONDITIONAL_LAMBDA_SCOPE_HELPER(type, cond) \
std::optional<LambdaScopeHandler> lambdaScopeHandler; \
if(cond) { \
lambdaScopeHandler.emplace(mLambdaStack, mOutputFormatHelper, LambdaCallerType::type); \
}
//-----------------------------------------------------------------------------
namespace ranges = std::ranges;
//-----------------------------------------------------------------------------
namespace clang::insights {
#define BUILD_OPT_AND(name, param) std::function name = [](param t) -> MyOptional<param>
#define BUILD_OPT_AND_O(name, param, ret) std::function name = [](param t) -> MyOptional<ret>
BUILD_OPT_AND(IsPointer, QualType)
{
if(t->isPointerType()) {
return t;
}
return {};
};
BUILD_OPT_AND(IsPOD, QualType)
{
if(t.isPODType(GetGlobalAST())) {
return t;
}
return {};
};
template<typename T>
std::function Isa = [](QualType t) -> MyOptional<QualType> {
if(isa<T>(t.getTypePtrOrNull())) {
return t;
}
return {};
};
BUILD_OPT_AND_O(CanonicalType, const InitListExpr&, QualType)
{
return t.getType().getCanonicalType();
};
static std::string AccessToStringWithColon(const AccessSpecifier& access)
{
std::string accessStr{getAccessSpelling(access)};
if(not accessStr.empty()) {
accessStr += ": "sv;
}
return accessStr;
}
//-----------------------------------------------------------------------------
using namespace asthelpers;
static std::string_view GetCastName(const CastKind castKind, bool constnessChange = false)
{
if(is{castKind}.any_of(CastKind::CK_BitCast, CastKind::CK_IntegralToPointer, CastKind::CK_PointerToIntegral)) {
return kwReinterpretCast;
}
if((CastKind::CK_NoOp == castKind) and constnessChange) {
return "const_cast"sv;
}
return kwStaticCast;
}
//-----------------------------------------------------------------------------
static std::string_view GetTagDeclTypeName(const TagDecl& decl)
{
if(decl.isClass()) {
return kwClassSpace;
} else if(decl.isUnion()) {
return kwUnionSpace;
} else {
return kwStructSpace;
}
}
//-----------------------------------------------------------------------------
class ArrayInitCodeGenerator final : public CodeGenerator
{
const uint64_t mIndex;
public:
ArrayInitCodeGenerator(OutputFormatHelper& _outputFormatHelper, const uint64_t index)
: CodeGenerator{_outputFormatHelper}
, mIndex{index}
{
}
using CodeGenerator::InsertArg;
void InsertArg(const ArrayInitIndexExpr*) override { mOutputFormatHelper.Append(mIndex); }
};
//-----------------------------------------------------------------------------
/// Handling specialties for decomposition declarations.
///
/// Decompositions declarations have no name. This class stores the made up name and returns it each time the anonymous
/// declaration is asked for a name.
class StructuredBindingsCodeGenerator final : public CodeGenerator
{
std::string mVarName;
public:
StructuredBindingsCodeGenerator(OutputFormatHelper& _outputFormatHelper, std::string&& varName)
: CodeGenerator{_outputFormatHelper}
, mVarName{std::move(varName)}
{
}
using CodeGenerator::InsertArg;
void InsertArg(const DeclRefExpr* stmt) override;
void InsertArg(const BindingDecl* stmt) override;
/// Inserts the bindings of a decompositions declaration.
void InsertDecompositionBindings(const DecompositionDecl& decompositionDeclStmt);
protected:
virtual bool ShowXValueCasts() const override { return true; }
};
//-----------------------------------------------------------------------------
/// Handle using statements which pull functions ore members from a base class into the class.
class UsingCodeGenerator final : public CodeGenerator
{
public:
UsingCodeGenerator(OutputFormatHelper& _outputFormatHelper)
: CodeGenerator{_outputFormatHelper}
{
}
using CodeGenerator::InsertArg;
void InsertArg(const CXXMethodDecl* stmt) override
{
mOutputFormatHelper.Append(kwCppCommentStartSpace);
InsertCXXMethodDecl(stmt, SkipBody::Yes);
}
void InsertArg(const FieldDecl* stmt) override
{
mOutputFormatHelper.Append(kwCppCommentStartSpace);
CodeGenerator::InsertArg(stmt);
}
// makes no sense to insert the class when applying it to using
void InsertArg(const CXXRecordDecl*) override {}
// makes no sense to insert the typedef when applying it to using
void InsertArg(const TypedefDecl*) override {}
protected:
bool InsertNamespace() const override { return true; }
};
//-----------------------------------------------------------------------------
/// \brief A special code generator for Lambda init captures which use \c std::move
class LambdaInitCaptureCodeGenerator final : public CodeGenerator
{
public:
explicit LambdaInitCaptureCodeGenerator(OutputFormatHelper& outputFormatHelper,
LambdaStackType& lambdaStack,
std::string_view varName)
: CodeGenerator{outputFormatHelper, lambdaStack, ProcessingPrimaryTemplate::No}
, mVarName{varName}
{
}
using CodeGenerator::InsertArg;
/// Replace every \c VarDecl with the given variable name. This cover init captures which introduce a new name.
/// However, it means that _all_ VarDecl's will be changed.
/// TODO: Check if it is really good to replace all VarDecl's
void InsertArg(const DeclRefExpr* stmt) override
{
if(isa<VarDecl>(stmt->getDecl())) {
mOutputFormatHelper.Append("_"sv, mVarName);
} else {
CodeGenerator::InsertArg(stmt);
}
}
private:
std::string_view mVarName; ///< The name of the variable that needs to be prefixed with _.
};
//-----------------------------------------------------------------------------
class LambdaNameOnlyCodeGenerator final : public CodeGenerator
{
public:
using CodeGenerator::CodeGenerator;
using CodeGenerator::InsertArg;
void InsertArg(const LambdaExpr* stmt) override { mOutputFormatHelper.Append(GetLambdaName(*stmt), "{}"sv); }
};
//-----------------------------------------------------------------------------
CodeGenerator::LambdaScopeHandler::LambdaScopeHandler(LambdaStackType& stack,
OutputFormatHelper& outputFormatHelper,
const LambdaCallerType lambdaCallerType)
: mStack{stack}
, mHelper{lambdaCallerType, GetBuffer(outputFormatHelper)}
{
mStack.push(mHelper);
}
//-----------------------------------------------------------------------------
CodeGenerator::LambdaScopeHandler::~LambdaScopeHandler()
{
if(not mStack.empty()) {
mStack.pop()->finish();
}
}
//-----------------------------------------------------------------------------
OutputFormatHelper& CodeGenerator::LambdaScopeHandler::GetBuffer(OutputFormatHelper& outputFormatHelper) const
{
// Find the most outer element to place the lambda class definition. For example, if we have this:
// Test( [&]() {} );
// The lambda's class definition needs to be placed _before_ the CallExpr to Test.
for(auto& l : mStack) {
switch(l.callerType()) {
case LambdaCallerType::CallExpr: [[fallthrough]];
case LambdaCallerType::VarDecl: [[fallthrough]];
case LambdaCallerType::ReturnStmt: [[fallthrough]];
case LambdaCallerType::OperatorCallExpr: [[fallthrough]];
case LambdaCallerType::MemberCallExpr: [[fallthrough]];
case LambdaCallerType::BinaryOperator: [[fallthrough]];
case LambdaCallerType::CXXMethodDecl: return l.buffer();
default: break;
}
}
return outputFormatHelper;
}
//-----------------------------------------------------------------------------
static std::string_view ArrowOrDot(bool isArrow)
{
return isArrow ? "->"sv : "."sv;
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const CXXDependentScopeMemberExpr* stmt)
{
if(not stmt->isImplicitAccess()) {
InsertArg(stmt->getBase());
} else {
InsertNamespace(stmt->getQualifier());
}
auto op{[&]() -> std::string_view {
if(stmt->isImplicitAccess()) {
return {};
}
return ArrowOrDot(stmt->isArrow());
}()};
mOutputFormatHelper.Append(op, stmt->getMemberNameInfo().getAsString());
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const CXXForRangeStmt* rangeForStmt)
{
auto& langOpts{GetLangOpts(*rangeForStmt->getLoopVariable())};
const bool onlyCpp11{not langOpts.CPlusPlus17};
auto* rwStmt = const_cast<CXXForRangeStmt*>(rangeForStmt);
StmtsContainer outerScopeStmts{};
// C++20 init-statement
outerScopeStmts.Add(rangeForStmt->getInit());
// range statement
outerScopeStmts.Add(rangeForStmt->getRangeStmt());
if(not onlyCpp11) {
outerScopeStmts.Add(rangeForStmt->getBeginStmt());
outerScopeStmts.Add(rangeForStmt->getEndStmt());
}
// add the loop variable to the body
StmtsContainer bodyStmts{};
bodyStmts.Add(rangeForStmt->getLoopVarStmt());
// add the body itself, without the CompoundStmt
bodyStmts.AddBodyStmts(rwStmt->getBody());
const auto& ctx = rangeForStmt->getLoopVariable()->getASTContext();
// In case of a range-based for-loop inside an unevaluated template the begin and end statements are not present. In
// this case just add a nullptr.
auto* declStmt = [&]() -> DeclStmt* {
if(onlyCpp11) {
return mkDeclStmt(rwStmt->getBeginStmt() ? rwStmt->getBeginStmt()->getSingleDecl() : nullptr,
rwStmt->getEndStmt() ? rwStmt->getEndStmt()->getSingleDecl() : nullptr);
}
return nullptr;
}();
auto* innerScope = mkCompoundStmt(bodyStmts, rangeForStmt->getBeginLoc(), rangeForStmt->getEndLoc());
auto* forStmt = new(ctx) ForStmt(ctx,
declStmt,
rwStmt->getCond(),
rwStmt->getLoopVariable(),
rwStmt->getInc(),
innerScope,
rangeForStmt->getBeginLoc(),
rangeForStmt->getEndLoc(),
rangeForStmt->getEndLoc());
outerScopeStmts.Add(forStmt);
auto* outerScope = mkCompoundStmt(outerScopeStmts, rangeForStmt->getBeginLoc(), rangeForStmt->getEndLoc());
InsertArg(outerScope);
mOutputFormatHelper.AppendNewLine();
}
//-----------------------------------------------------------------------------
template<typename T>
static T ValueOrDefault(bool b, T v)
{
if(b) {
return v;
}
return {};
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertQualifierAndName(const DeclarationName& declName,
const NestedNameSpecifier* qualifier,
const bool hasTemplateKeyword)
{
mOutputFormatHelper.Append(ScopeHandler::RemoveCurrentScope(GetNestedName(qualifier)),
ValueOrDefault(hasTemplateKeyword, kwTemplateSpace),
declName.getAsString());
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertNamespace(const NestedNameSpecifier* stmt)
{
mOutputFormatHelper.Append(ScopeHandler::RemoveCurrentScope(GetNestedName(stmt)));
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const UnresolvedLookupExpr* stmt)
{
InsertQualifierAndNameWithTemplateArgs(stmt->getName(), stmt);
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const DependentScopeDeclRefExpr* stmt)
{
InsertQualifierAndNameWithTemplateArgs(stmt->getDeclName(), stmt);
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const VarTemplateDecl* stmt)
{
const auto* templatedDecl = stmt->getTemplatedDecl();
// Insert only the primary template here. The specializations are inserted via their instantiated
// VarTemplateSpecializationDecl which resolved to a VarDecl. It looks like whether the variable has an initializer
// or not can be used to distinguish between the primary template and one appearing in a templated class.
RETURN_IF(not templatedDecl->hasInit());
// VarTemplatedDecl's can have lambdas as initializers. Push a VarDecl on the stack, otherwise the lambda would
// appear in the middle of template<....> and the variable itself.
{
LAMBDA_SCOPE_HELPER(Decltype); // Needed for P0315Checker
mLambdaStack.back().setInsertName(true);
InsertTemplateParameters(*stmt->getTemplateParameters());
}
LAMBDA_SCOPE_HELPER(VarDecl);
InsertArg(templatedDecl);
OnceTrue first{};
for(const auto* spec : stmt->specializations()) {
if(TSK_ExplicitSpecialization == spec->getSpecializationKind()) {
continue;
}
if(first) {
mOutputFormatHelper.AppendNewLine();
}
InsertArg(spec);
}
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const ConceptDecl* stmt)
{
LAMBDA_SCOPE_HELPER(Decltype);
InsertTemplateParameters(*stmt->getTemplateParameters());
mOutputFormatHelper.Append(kwConceptSpace, stmt->getName(), hlpAssing);
InsertArg(stmt->getConstraintExpr());
mOutputFormatHelper.AppendSemiNewLine();
mOutputFormatHelper.AppendNewLine();
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const ConditionalOperator* stmt)
{
InsertArg(stmt->getCond());
mOutputFormatHelper.Append(" ? "sv);
InsertArg(stmt->getLHS());
mOutputFormatHelper.Append(" : "sv);
InsertArg(stmt->getRHS());
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const DoStmt* stmt)
{
mOutputFormatHelper.Append(kwDoSpace);
WrapInCompoundIfNeeded(stmt->getBody(), AddNewLineAfter::No);
mOutputFormatHelper.Append(kwWhile);
WrapInParens([&]() { InsertArg(stmt->getCond()); }, AddSpaceAtTheEnd::No);
mOutputFormatHelper.AppendSemiNewLine();
mOutputFormatHelper.AppendNewLine();
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const CaseStmt* stmt)
{
mOutputFormatHelper.Append(kwCaseSpace);
InsertArg(stmt->getLHS());
mOutputFormatHelper.Append(": "sv);
InsertArg(stmt->getSubStmt());
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const BreakStmt* /*stmt*/)
{
mOutputFormatHelper.Append(kwBreak);
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const DefaultStmt* stmt)
{
mOutputFormatHelper.Append("default: "sv);
InsertArg(stmt->getSubStmt());
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const ContinueStmt* /*stmt*/)
{
mOutputFormatHelper.Append(kwContinue);
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const GotoStmt* stmt)
{
mOutputFormatHelper.Append(kwGotoSpace);
InsertArg(stmt->getLabel());
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const LabelStmt* stmt)
{
mOutputFormatHelper.AppendNewLine(stmt->getName(), ":"sv);
if(stmt->getSubStmt()) {
InsertArg(stmt->getSubStmt());
}
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const SwitchStmt* stmt)
{
const bool hasInit{stmt->getInit() or stmt->getConditionVariable()};
if(hasInit) {
mOutputFormatHelper.OpenScope();
InsertIfOrSwitchInitVariables(stmt);
}
mOutputFormatHelper.Append(kwSwitch);
WrapInParens([&]() { InsertArg(stmt->getCond()); }, AddSpaceAtTheEnd::Yes);
InsertArg(stmt->getBody());
if(hasInit) {
mOutputFormatHelper.CloseScope();
}
mOutputFormatHelper.AppendNewLine();
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const WhileStmt* stmt)
{
{
// We need to handle the case that a lambda is used in the init-statement of the for-loop.
LAMBDA_SCOPE_HELPER(VarDecl);
mOutputFormatHelper.Append(kwWhile);
WrapInParens([&]() { InsertArg(stmt->getCond()); }, AddSpaceAtTheEnd::Yes);
}
WrapInCompoundIfNeeded(stmt->getBody(), AddNewLineAfter::Yes);
mOutputFormatHelper.AppendNewLine();
}
//-----------------------------------------------------------------------------
/// Get the name of a \c FieldDecl in case this \c FieldDecl is part of a lambda. The name has to be retrieved from the
/// capture fields or can be \c __this.
static std::optional<std::string> GetFieldDeclNameForLambda(const FieldDecl& fieldDecl,
const CXXRecordDecl& cxxRecordDecl)
{
if(cxxRecordDecl.isLambda()) {
llvm::DenseMap<const
#if IS_CLANG_NEWER_THAN(15)
ValueDecl*
#else
VarDecl*
#endif
,
FieldDecl*>
captures{};
FieldDecl* thisCapture{};
cxxRecordDecl.getCaptureFields(captures, thisCapture);
if(&fieldDecl == thisCapture) {
return std::string{kwInternalThis};
} else {
for(const auto& [key, value] : captures) {
if(&fieldDecl == value) {
return GetName(*key);
}
}
}
}
return {};
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const SourceLocExpr* stmt)
{
mOutputFormatHelper.Append(stmt->getBuiltinStr(), "()"sv);
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const MemberExpr* stmt)
{
const auto* base = stmt->getBase();
const bool skipBase{[&] {
if(const auto* implicitCast = dyn_cast_or_null<ImplicitCastExpr>(base)) {
if(CastKind::CK_UncheckedDerivedToBase == implicitCast->getCastKind()) {
// if this calls a protected function we cannot cast it to the base, this would not compile
if(isa<CXXThisExpr>(implicitCast->IgnoreImpCasts())) {
return true;
}
}
}
return false;
}()};
if(skipBase) {
mOutputFormatHelper.Append(kwCCommentStartSpace);
}
InsertArg(base);
const auto* meDecl = stmt->getMemberDecl();
bool skipTemplateArgs{false};
const auto name = [&]() -> std::string {
// Handle a special case where we have a lambda static invoke operator. In that case use the appropriate
// using retType as return type
if(const auto* m = dyn_cast_or_null<CXXMethodDecl>(meDecl)) {
if(const auto* rd = m->getParent(); rd and rd->isLambda() and isa<CXXConversionDecl>(m)) {
skipTemplateArgs = true;
return StrCat(kwOperatorSpace, GetLambdaName(*rd), "::"sv, BuildRetTypeName(*rd));
}
}
// This is at least the case for lambdas, where members are created by capturing a structured binding. See #181.
else if(const auto* fd = dyn_cast_or_null<FieldDecl>(meDecl)) {
if(const auto* cxxRecordDecl = dyn_cast_or_null<CXXRecordDecl>(fd->getParent())) {
if(const auto& fieldName = GetFieldDeclNameForLambda(*fd, *cxxRecordDecl)) {
return fieldName.value();
}
}
}
// Special case. If this is a CXXConversionDecl it might be:
// a) a template so we need the template arguments from this type
// b) in a namespace and need want to preserve that one.
if(const auto* convDecl = dyn_cast_or_null<CXXConversionDecl>(meDecl)) {
return StrCat(kwOperatorSpace, GetName(convDecl->getConversionType()));
}
return stmt->getMemberNameInfo().getName().getAsString();
}();
mOutputFormatHelper.Append(ArrowOrDot(stmt->isArrow()));
if(skipBase) {
mOutputFormatHelper.Append(kwSpaceCCommentEndSpace);
}
mOutputFormatHelper.Append(name);
RETURN_IF(skipTemplateArgs);
if(const auto cxxMethod = dyn_cast_or_null<CXXMethodDecl>(meDecl)) {
if(const auto* tmplArgs = cxxMethod->getTemplateSpecializationArgs()) {
OutputFormatHelper ofm{};
ofm.Append('<');
bool haveArg{false};
OnceFalse needsComma{};
for(const auto& arg : tmplArgs->asArray()) {
if(arg.getKind() == TemplateArgument::Integral) {
ofm.AppendComma(needsComma);
ofm.Append(arg.getAsIntegral());
haveArg = true;
} else {
break;
}
}
if(haveArg) {
mOutputFormatHelper.Append(ofm, ">"sv);
} else if(not isa<CXXConversionDecl>(meDecl)) { // A special case from p0892 a templated conversion
// operator does not carry the specialization args...
InsertTemplateArgs(*tmplArgs);
}
}
}
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const UnaryExprOrTypeTraitExpr* stmt)
{
mOutputFormatHelper.Append(std::string_view{getTraitSpelling(stmt->getKind())});
if(not stmt->isArgumentType()) {
const auto* argExpr = stmt->getArgumentExpr();
const bool needsParens{not isa<ParenExpr>(argExpr)};
WrapInParensIfNeeded(needsParens, [&] { InsertArg(argExpr); });
} else {
WrapInParens([&] { mOutputFormatHelper.Append(GetName(stmt->getTypeOfArgument())); });
}
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const IntegerLiteral* stmt)
{
const auto& type = stmt->getType();
const bool isSigned = type->isSignedIntegerType();
mOutputFormatHelper.Append(llvm::toString(stmt->getValue(), 10, isSigned));
InsertSuffix(type);
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const FloatingLiteral* stmt)
{
// FIXME: not working correctly
mOutputFormatHelper.Append(EvaluateAsFloat(*stmt));
InsertSuffix(stmt->getType());
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const CXXTypeidExpr* stmt)
{
mOutputFormatHelper.Append(kwTypeId);
WrapInParens([&]() {
if(stmt->isTypeOperand()) {
mOutputFormatHelper.Append(GetName(stmt->getTypeOperand(const_cast<ASTContext&>(GetGlobalAST()))));
} else {
InsertArg(stmt->getExprOperand());
}
});
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const BinaryOperator* stmt)
{
LAMBDA_SCOPE_HELPER(BinaryOperator);
BackupAndRestore _{mLastExpr, stmt->getLHS()};
const bool needLHSParens{isa<BinaryOperator>(stmt->getLHS()->IgnoreImpCasts())};
WrapInParensIfNeeded(needLHSParens, [&] { InsertArg(stmt->getLHS()); });
mOutputFormatHelper.Append(" "sv, stmt->getOpcodeStr(), " "sv);
const bool needRHSParens{isa<BinaryOperator>(stmt->getRHS()->IgnoreImpCasts())};
WrapInParensIfNeeded(needRHSParens, [&] { InsertArg(stmt->getRHS()); });
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const CompoundAssignOperator* stmt)
{
LAMBDA_SCOPE_HELPER(BinaryOperator);
const bool needLHSParens{isa<BinaryOperator>(stmt->getLHS()->IgnoreImpCasts())};
WrapInParensIfNeeded(needLHSParens, [&] { InsertArg(stmt->getLHS()); });
mOutputFormatHelper.Append(hlpAssing);
// we may need a cast around this back to the src type
const bool needCast{stmt->getLHS()->getType() != stmt->getComputationLHSType()};
if(needCast) {
mOutputFormatHelper.Append(kwStaticCast, "<"sv, GetName(stmt->getLHS()->getType()), ">("sv);
}
WrapInParensIfNeeded(needLHSParens, [&] {
clang::ExprResult res = stmt->getLHS();
// This cast is not present in the AST. However, if the LHS type is smaller than RHS there is an implicit cast
// to RHS-type and the result is casted back to LHS-type: static_cast<LHSTy>( static_cast<RHSTy>(LHS) + RHS )
if(const auto resultingType = GetGlobalCI().getSema().PrepareScalarCast(res, stmt->getComputationLHSType());
resultingType != CK_NoOp) {
const QualType castDestType = stmt->getComputationLHSType();
FormatCast(kwStaticCast, castDestType, stmt->getLHS(), resultingType);
} else {
InsertArg(stmt->getLHS());
}
});
mOutputFormatHelper.Append(
" "sv, BinaryOperator::getOpcodeStr(BinaryOperator::getOpForCompoundAssignment(stmt->getOpcode())), " "sv);
const bool needRHSParens{isa<BinaryOperator>(stmt->getRHS()->IgnoreImpCasts())};
WrapInParensIfNeeded(needRHSParens, [&] { InsertArg(stmt->getRHS()); });
if(needCast) {
mOutputFormatHelper.Append(")"sv);
}
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const CXXRewrittenBinaryOperator* stmt)
{
LAMBDA_SCOPE_HELPER(BinaryOperator);
InsertArg(stmt->getSemanticForm());
}
//-----------------------------------------------------------------------------
static std::string_view GetStorageClassAsString(const StorageClass& sc)
{
if(SC_None != sc) {
return VarDecl::getStorageClassSpecifierString(sc);
}
return {};
}
//-----------------------------------------------------------------------------
static std::string GetStorageClassAsStringWithSpace(const StorageClass& sc)
{
std::string ret{GetStorageClassAsString(sc)};
if(not ret.empty()) {
ret.append(" "sv);
}
return ret;
}
//-----------------------------------------------------------------------------
static std::string GetQualifiers(const VarDecl& vd)
{
std::string qualifiers{};
if(vd.isInline() or vd.isInlineSpecified()) {
qualifiers += kwInlineSpace;
}
qualifiers += GetStorageClassAsStringWithSpace(vd.getStorageClass());
if(vd.isConstexpr()) {
qualifiers += kwConstExprSpace;
}
return qualifiers;
}
//-----------------------------------------------------------------------------
static std::string FormatVarTemplateSpecializationDecl(const Decl* decl, std::string&& defaultName)
{
std::string name{std::move(defaultName)};
if(const auto* tvd = dyn_cast_or_null<VarTemplateSpecializationDecl>(decl)) {
OutputFormatHelper outputFormatHelper{};
CodeGeneratorVariant codeGenerator{outputFormatHelper};
codeGenerator->InsertTemplateArgs(tvd->getTemplateArgs());
name += outputFormatHelper;
}
return name;
}
//-----------------------------------------------------------------------------
/// \brief Find a \c DeclRefExpr belonging to a \c DecompositionDecl
class BindingDeclFinder : public ConstStmtVisitor<BindingDeclFinder>
{
bool mIsBinding{};
public:
BindingDeclFinder() = default;
void VisitDeclRefExpr(const DeclRefExpr* expr)
{
if(isa<DecompositionDecl>(expr->getDecl())) {
mIsBinding = true;
}
}
void VisitStmt(const Stmt* stmt)
{
for(const auto* child : stmt->children()) {
if(child) {
Visit(child);
}
RETURN_IF(mIsBinding);
}
}
bool Find(const Stmt* stmt)
{
if(stmt) {
VisitStmt(stmt);
}
return mIsBinding;
}
};
//-----------------------------------------------------------------------------
/// \brief Find a \c DeclRefExpr belonging to a \c DecompositionDecl
class TemporaryDeclFinder : public StmtVisitor<TemporaryDeclFinder>
{
CodeGenerator& codeGenerator;
bool mFound{};
bool mHaveTemporary{};
Stmt* mPrevStmt{};
std::string mTempName{};
public:
TemporaryDeclFinder(CodeGenerator& _codeGenerator, const Stmt* stmt, bool inspectReturn = false)
: codeGenerator{_codeGenerator}
, mPrevStmt{const_cast<Stmt*>(stmt)}
{
RETURN_IF(not GetInsightsOptions().ShowLifetime);
Visit(mPrevStmt);
RETURN_IF(not GetInsightsOptions().UseShow2C or mFound or not inspectReturn);
if(auto* expr = dyn_cast_or_null<CXXConstructExpr>(stmt)) {
mTempName = GetTemporaryName(*expr);
#if 0
auto* dummy = Function("dummy"sv, VoidTy(), {});
auto* vd = Variable(mTempName, expr->getType(), dummy->getDeclContext());
dummy->getDeclContext()->addDecl(vd);
vd->setInit(const_cast<CXXConstructExpr*>(expr));
vd->setStorageClass(SC_None);
#else
// XXX hack. Our normal VarDecl is at TU level. It then appears in cxa_start...
auto& ctx = GetGlobalAST();
auto* vd = ImplicitParamDecl::Create(const_cast<ASTContext&>(ctx),
ctx.getTranslationUnitDecl(),
{},
&ctx.Idents.get(mTempName),
expr->getType(),
#if IS_CLANG_NEWER_THAN(17)
ImplicitParamKind::Other
#else
ImplicitParamDecl::Other
#endif
);
#endif
mFound = true;
codeGenerator.InsertArg(vd);
} else if(auto* expr = dyn_cast_or_null<InitListExpr>(stmt)) {
mTempName = GetTemporaryName(*expr);
auto* vd = Variable(mTempName, expr->getType());
vd->setInit(const_cast<InitListExpr*>(expr));
mFound = true;
codeGenerator.InsertArg(vd);
}
}
~TemporaryDeclFinder()
{
if(mHaveTemporary) {
codeGenerator.EndLifetimeScope();
}
}
bool Found() const { return mFound; }
std::string Name() const { return mTempName; }
void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr* expr)
{
mTempName = GetName(*expr);
mFound = true;
auto* vd = Variable(mTempName, expr->getType());
// In the Cfront case the contents of the expression go after the generated constructor. In the lifetime
// _only_ case go with the variable.
if(not GetInsightsOptions().UseShow2C) {
// Since we insert the statement below we must clone this expression otherwise we look at a recursion.
auto* ctorConstructExpr = CXXConstructExpr::Create(GetGlobalAST(),
expr->getType(),
expr->getBeginLoc(),
expr->getConstructor(),
expr->isElidable(),
{expr->getArgs(), expr->getNumArgs()},
expr->hadMultipleCandidates(),
expr->isListInitialization(),