forked from andreasfertig/cppinsights
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CodeGenerator.cpp
2826 lines (2245 loc) · 94.8 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 "CodeGenerator.h"
#include <algorithm>
#include <vector>
#include "ClangCompat.h"
#include "DPrint.h"
#include "Insights.h"
#include "InsightsBase.h"
#include "InsightsHelpers.h"
#include "InsightsMatchers.h"
#include "InsightsOnce.h"
#include "InsightsStrCat.h"
#include "NumberIterator.h"
#include "clang/Frontend/CompilerInstance.h"
//-----------------------------------------------------------------------------
/// \brief Convenience macro to create a \ref LambdaScopeHandler on the stack.
#define LAMBDA_SCOPE_HELPER(type) \
LambdaScopeHandler lambdaScopeHandler{mLambdaStack, mOutputFormatHelper, LambdaCallerType::type};
//-----------------------------------------------------------------------------
namespace clang::insights {
static const char* AccessToString(const AccessSpecifier& access)
{
switch(access) {
case AS_public: return "public";
case AS_protected: return "protected";
case AS_private: return "private";
default: return "";
}
}
//-----------------------------------------------------------------------------
static std::string AccessToStringWithColon(const AccessSpecifier& access)
{
std::string accessStr = AccessToString(access);
if(!accessStr.empty()) {
accessStr += ": ";
}
return accessStr;
}
//-----------------------------------------------------------------------------
static std::string AccessToStringWithColon(const FunctionDecl& decl)
{
return AccessToStringWithColon(decl.getAccess());
}
//-----------------------------------------------------------------------------
static const char* GetCastName(const CastKind castKind)
{
if(CastKind::CK_BitCast == castKind) {
return "reinterpret_cast";
}
return "static_cast";
}
//-----------------------------------------------------------------------------
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;
/// Inserts the bindings of a decompositions declaration.
void InsertDecompositionBindings(const DecompositionDecl& decompositionDeclStmt);
};
//-----------------------------------------------------------------------------
CodeGenerator::LambdaScopeHandler::LambdaScopeHandler(LambdaStackType& stack,
OutputFormatHelper& outputFormatHelper,
const LambdaCallerType lambdaCallerType)
: mStack{stack}
, mHelper{lambdaCallerType, GetBuffer(outputFormatHelper)}
{
mStack.push(mHelper);
}
//-----------------------------------------------------------------------------
CodeGenerator::LambdaScopeHandler::~LambdaScopeHandler()
{
if(!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.
auto* element = [&]() -> LambdaHelper* {
for(auto& l : mStack) {
switch(l.callerType()) {
case LambdaCallerType::CallExpr:
case LambdaCallerType::VarDecl:
case LambdaCallerType::ReturnStmt:
case LambdaCallerType::OperatorCallExpr:
case LambdaCallerType::MemberCallExpr:
case LambdaCallerType::BinaryOperator: return &l;
default: break;
}
}
return nullptr;
}();
if(element) {
return element->buffer();
}
return outputFormatHelper;
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const CXXDependentScopeMemberExpr* stmt)
{
InsertArg(stmt->getBase());
const std::string op{stmt->isArrow() ? "->" : "."};
mOutputFormatHelper.Append(op, stmt->getMemberNameInfo().getAsString());
}
//-----------------------------------------------------------------------------
template<typename T>
static void AddStmt(std::vector<Stmt*>& v, const T& stmt)
{
if(stmt) {
v.push_back(const_cast<Stmt*>(static_cast<const Stmt*>(stmt)));
}
}
//-----------------------------------------------------------------------------
static void AddBodyStmts(std::vector<Stmt*>& v, Stmt* body)
{
if(auto* b = dyn_cast_or_null<CompoundStmt>(body)) {
for(auto* st : b->children()) {
v.push_back(st);
}
} else if(not isa<NullStmt>(body)) {
v.push_back(body);
}
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const CXXForRangeStmt* rangeForStmt)
{
auto& langOpts{GetLangOpts(*rangeForStmt->getLoopVariable())};
const bool onlyCpp11{not langOpts.CPlusPlus14};
auto* rwStmt = const_cast<CXXForRangeStmt*>(rangeForStmt);
std::vector<Stmt*> outerScopeStmts{};
std::vector<Stmt*> bodyStmts{};
// C++20 init-statement
AddStmt(outerScopeStmts, rangeForStmt->getInit());
// range statement
AddStmt(outerScopeStmts, rangeForStmt->getRangeStmt());
if(not onlyCpp11) {
AddStmt(outerScopeStmts, rangeForStmt->getBeginStmt());
AddStmt(outerScopeStmts, rangeForStmt->getEndStmt());
}
// add the loop variable to the body
AddStmt(bodyStmts, rangeForStmt->getLoopVarStmt());
// add the body itself, without the CompoundStmt
AddBodyStmts(bodyStmts, rwStmt->getBody());
const auto& ctx = rangeForStmt->getLoopVariable()->getASTContext();
Decl* decls[2]{rwStmt->getBeginStmt()->getSingleDecl(), rwStmt->getEndStmt()->getSingleDecl()};
auto dgRef = DeclGroupRef::Create(const_cast<ASTContext&>(ctx), decls, 2);
auto* declStmt = [&]() -> DeclStmt* {
if(onlyCpp11) {
return new(ctx) DeclStmt(dgRef, rangeForStmt->getBeginLoc(), rangeForStmt->getEndLoc());
}
return nullptr;
}();
ArrayRef<Stmt*> innerScopeStmtsRef{bodyStmts};
auto* innerScope =
CompoundStmt::Create(ctx, innerScopeStmtsRef, rangeForStmt->getBeginLoc(), rangeForStmt->getEndLoc());
auto* forStmt = new(ctx) ForStmt(ctx,
declStmt,
rwStmt->getCond(),
rwStmt->getLoopVariable(),
rwStmt->getInc(),
innerScope,
rangeForStmt->getBeginLoc(),
rangeForStmt->getEndLoc(),
rangeForStmt->getEndLoc());
AddStmt(outerScopeStmts, forStmt);
ArrayRef<Stmt*> outerScopeStmtsRef{outerScopeStmts};
auto* outerScope =
CompoundStmt::Create(ctx, outerScopeStmtsRef, rangeForStmt->getBeginLoc(), rangeForStmt->getEndLoc());
InsertArg(outerScope);
mOutputFormatHelper.AppendNewLine();
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const UnresolvedLookupExpr* stmt)
{
mOutputFormatHelper.Append(stmt->getName().getAsString());
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const ConditionalOperator* stmt)
{
InsertArg(stmt->getCond());
mOutputFormatHelper.Append(" ? ");
InsertArg(stmt->getLHS());
mOutputFormatHelper.Append(" : ");
InsertArg(stmt->getRHS());
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const DoStmt* stmt)
{
mOutputFormatHelper.Append("do ");
const auto* body = stmt->getBody();
InsertArg(body);
if(isa<CompoundStmt>(body)) {
mOutputFormatHelper.Append(' ');
} else if(!isa<NullStmt>(body)) {
mOutputFormatHelper.Append("; ");
}
mOutputFormatHelper.Append("while");
WrapInParens([&]() { InsertArg(stmt->getCond()); }, AddSpaceAtTheEnd::No);
mOutputFormatHelper.AppendSemiNewLine();
mOutputFormatHelper.AppendNewLine();
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const CaseStmt* stmt)
{
mOutputFormatHelper.Append("case ");
InsertArg(stmt->getLHS());
// TODO what is getRHS??
mOutputFormatHelper.Append(": ");
InsertArg(stmt->getSubStmt());
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const BreakStmt* /*stmt*/)
{
mOutputFormatHelper.Append("break");
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const DefaultStmt* stmt)
{
mOutputFormatHelper.Append("default: ");
InsertArg(stmt->getSubStmt());
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const ContinueStmt* /*stmt*/)
{
mOutputFormatHelper.Append("continue");
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const GotoStmt* stmt)
{
mOutputFormatHelper.Append("goto ");
InsertArg(stmt->getLabel());
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const LabelStmt* stmt)
{
mOutputFormatHelper.AppendNewLine(stmt->getName(), ":");
if(stmt->getSubStmt()) {
InsertArg(stmt->getSubStmt());
}
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const SwitchStmt* stmt)
{
const bool hasInit{stmt->getInit() || stmt->getConditionVariable()};
if(hasInit) {
mOutputFormatHelper.OpenScope();
if(const auto* conditionVar = stmt->getConditionVariable()) {
InsertArg(conditionVar);
}
if(const auto* init = stmt->getInit()) {
InsertArg(init);
}
}
mOutputFormatHelper.Append("switch");
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("while");
WrapInParens([&]() { InsertArg(stmt->getCond()); }, AddSpaceAtTheEnd::Yes);
}
const auto* body = stmt->getBody();
const bool hasCompoundStmt{isa<CompoundStmt>(body)};
InsertArg(body);
if(hasCompoundStmt) {
mOutputFormatHelper.AppendNewLine();
} else {
const bool isBodyBraced = isa<CompoundStmt>(body);
if(!isBodyBraced) {
mOutputFormatHelper.AppendSemiNewLine();
}
}
mOutputFormatHelper.AppendNewLine();
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const MemberExpr* stmt)
{
const auto* base = stmt->getBase();
bool skipBase{false};
if(const auto* implicitCast = dyn_cast_or_null<ImplicitCastExpr>(base)) {
if(CastKind::CK_UncheckedDerivedToBase == implicitCast->getCastKind()) {
const auto* castDest = implicitCast->IgnoreImpCasts();
// if this calls a protected function we cannot cast it to the base, this would not compile
if(isa<CXXThisExpr>(castDest)) {
skipBase = true;
}
}
}
if(skipBase) {
mOutputFormatHelper.Append("/* ");
}
InsertArg(base);
const std::string op{stmt->isArrow() ? "->" : "."};
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 && rd->isLambda()) {
skipTemplateArgs = true;
return StrCat("operator ", GetLambdaName(*rd), "::", BuildRetTypeName(*rd));
}
}
return stmt->getMemberNameInfo().getName().getAsString();
}();
mOutputFormatHelper.Append(op);
if(skipBase) {
mOutputFormatHelper.Append(" */ ");
}
mOutputFormatHelper.Append(name);
if(!skipTemplateArgs) {
if(const auto cxxMethod = dyn_cast_or_null<CXXMethodDecl>(meDecl)) {
if(const auto* tmplArgs = cxxMethod->getAsFunction()->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.GetString(), ">");
}
}
}
}
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const UnaryExprOrTypeTraitExpr* stmt)
{
mOutputFormatHelper.Append(GetKind(*stmt));
if(!stmt->isArgumentType()) {
const auto* argExpr = stmt->getArgumentExpr();
const bool needsParens{!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(stmt->getValue().toString(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("typeid");
WrapInParens([&]() {
if(stmt->isTypeOperand()) {
mOutputFormatHelper.Append(GetName(stmt->getType()));
} else {
InsertArg(stmt->getExprOperand());
}
});
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const BinaryOperator* stmt)
{
LAMBDA_SCOPE_HELPER(BinaryOperator);
InsertArg(stmt->getLHS());
mOutputFormatHelper.Append(" ", stmt->getOpcodeStr(), " ");
// For + and - add the parentheses, if not already supplied. It looks like fold-expression to not carry them.
const bool needParens{
isa<BinaryOperator>(stmt->getRHS()->IgnoreImpCasts()) &&
((BinaryOperatorKind::BO_Add == stmt->getOpcode()) || (BinaryOperatorKind::BO_Sub == stmt->getOpcode()))};
WrapInParensIfNeeded(needParens, [&] { InsertArg(stmt->getRHS()); });
}
//-----------------------------------------------------------------------------
static const char* 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(!ret.empty()) {
ret.append(" ");
}
return ret;
}
//-----------------------------------------------------------------------------
static std::string GetQualifiers(const VarDecl& vd)
{
std::string qualifiers{};
if(vd.isInline() || vd.isInlineSpecified()) {
qualifiers += "inline ";
}
qualifiers += GetStorageClassAsStringWithSpace(vd.getStorageClass());
if(vd.isConstexpr()) {
qualifiers += "constexpr ";
}
return qualifiers;
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const VarDecl* stmt)
{
LAMBDA_SCOPE_HELPER(VarDecl);
if(InsertComma()) {
mOutputFormatHelper.Append(',');
}
if(isa<VarTemplateSpecializationDecl>(stmt)) {
mOutputFormatHelper.AppendNewLine("template<>");
}
if(IsTrivialStaticClassVarDecl(*stmt)) {
HandleLocalStaticNonTrivialClass(stmt);
} else {
if(InsertVarDecl()) {
mOutputFormatHelper.Append(GetQualifiers(*stmt));
if(const auto type = stmt->getType(); type->isFunctionPointerType()) {
const auto lineNo = GetSM(*stmt).getSpellingLineNumber(stmt->getSourceRange().getBegin());
const std::string funcPtrName{StrCat("FuncPtr_", lineNo, " ")};
mOutputFormatHelper.AppendNewLine("using ", funcPtrName, "= ", GetName(type), ";");
mOutputFormatHelper.Append(funcPtrName, GetName(*stmt));
} else {
const auto varName = [&]() {
std::string name{GetName(*stmt)};
if(const auto* tvd = dyn_cast_or_null<VarTemplateSpecializationDecl>(stmt)) {
OutputFormatHelper outputFormatHelper{};
CodeGenerator codeGenerator{outputFormatHelper};
codeGenerator.InsertTemplateArgs(tvd->getTemplateArgs().asArray());
name += outputFormatHelper.GetString();
}
return name;
}();
// TODO: to keep the special handling for lambdas, do this only for template specializations
if(stmt->getType()->getAs<TemplateSpecializationType>()) {
mOutputFormatHelper.Append(GetNameAsWritten(stmt->getType()), " ", varName);
} else {
mOutputFormatHelper.Append(GetTypeNameAsParameter(stmt->getType(), varName));
}
}
} else {
const std::string pointer = [&]() {
if(stmt->getType()->isAnyPointerType()) {
return " *";
}
return " ";
}();
mOutputFormatHelper.Append(pointer, GetName(*stmt));
}
if(stmt->hasInit()) {
mOutputFormatHelper.Append(" = ");
InsertArg(stmt->getInit());
};
if(stmt->isNRVOVariable()) {
mOutputFormatHelper.Append(" /* NRVO variable */");
}
if(InsertSemi()) {
mOutputFormatHelper.AppendSemiNewLine();
}
// Insert the bindings of a DecompositionDecl if this VarDecl is a DecompositionDecl.
if(const auto* decompDecl = dyn_cast_or_null<DecompositionDecl>(stmt)) {
StructuredBindingsCodeGenerator codeGenerator{mOutputFormatHelper, GetName(*stmt)};
codeGenerator.InsertDecompositionBindings(*decompDecl);
}
}
}
//-----------------------------------------------------------------------------
bool CodeGenerator::InsertLambdaStaticInvoker(const CXXMethodDecl* cxxMethodDecl)
{
if(cxxMethodDecl && cxxMethodDecl->isLambdaStaticInvoker()) {
mOutputFormatHelper.AppendNewLine();
const auto* lambda = cxxMethodDecl->getParent();
const auto* callOp = lambda->getLambdaCallOperator();
if(lambda->isGenericLambda() && cxxMethodDecl->isFunctionTemplateSpecialization()) {
const TemplateArgumentList* tal = cxxMethodDecl->getTemplateSpecializationArgs();
FunctionTemplateDecl* callOpTemplate = callOp->getDescribedFunctionTemplate();
void* insertPos = nullptr;
FunctionDecl* correspondingCallOpSpecialization =
callOpTemplate->findSpecialization(tal->asArray(), insertPos);
callOp = cast<CXXMethodDecl>(correspondingCallOpSpecialization);
}
InsertArg(callOp->getBody());
mOutputFormatHelper.AppendNewLine();
return true;
}
return false;
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const FunctionDecl* stmt)
{
// LAMBDA_SCOPE_HELPER(VarDecl);
if(const auto* ctor = dyn_cast_or_null<CXXConstructorDecl>(stmt)) {
InsertArg(ctor);
} else {
InsertAccessModifierAndNameWithReturnType(*stmt, SkipAccess::Yes);
if(not InsertLambdaStaticInvoker(dyn_cast_or_null<CXXMethodDecl>(stmt))) {
if(stmt->doesThisDeclarationHaveABody()) {
mOutputFormatHelper.AppendNewLine();
InsertArg(stmt->getBody());
mOutputFormatHelper.AppendNewLine();
} else {
mOutputFormatHelper.AppendSemiNewLine();
}
}
}
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const ParenListExpr* stmt)
{
OnceFalse needsComma{};
for(const auto& expr : stmt->children()) {
mOutputFormatHelper.AppendComma(needsComma);
InsertArg(expr);
}
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const InitListExpr* stmt)
{
WrapInCurlys([&]() {
mOutputFormatHelper.IncreaseIndent();
ForEachArg(stmt->inits(), [&](const auto& init) { InsertArg(init); });
// If we have a filler, fill the rest of the array with the filler expr.
if(const auto* filler = stmt->getArrayFiller()) {
const auto fullWidth = [&]() -> uint64_t {
if(const auto* ct = dyn_cast_or_null<ConstantArrayType>(stmt->getType().getTypePtrOrNull())) {
const auto v = ct->getSize().getZExtValue();
// clamp here to survive large arrays.
return std::clamp(v, uint64_t(0), uint64_t(100));
}
return 0;
}();
// now fill the remaining array slots.
OnceFalse needsComma{0 != stmt->getNumInits()};
for_each(static_cast<uint64_t>(stmt->getNumInits()), fullWidth, [&](auto) {
mOutputFormatHelper.AppendComma(needsComma);
InsertArg(filler);
});
}
});
mOutputFormatHelper.DecreaseIndent();
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const CXXDefaultInitExpr* stmt)
{
const auto* subExpr = stmt->getExpr();
InsertCurlysIfRequired(subExpr);
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const CXXDeleteExpr* stmt)
{
mOutputFormatHelper.Append("delete");
if(stmt->isArrayForm()) {
mOutputFormatHelper.Append("[]");
}
mOutputFormatHelper.Append(' ');
InsertArg(stmt->getArgument());
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const CXXConstructExpr* stmt)
{
mOutputFormatHelper.Append(GetName(GetDesugarType(stmt->getType()), Unqualified::Yes));
const BraceKind braceKind = [&]() {
if(stmt->isListInitialization()) {
return BraceKind::Curlys;
}
return BraceKind::Parens;
}();
WrapInParensOrCurlys(braceKind, [&]() {
if(stmt->getNumArgs()) {
ForEachArg(stmt->arguments(), [&](const auto& arg) { InsertArg(arg); });
}
});
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const CXXInheritedCtorInitExpr* stmt)
{
const auto& constructorDecl = *stmt->getConstructor();
mOutputFormatHelper.Append(GetName(GetDesugarType(stmt->getType()), Unqualified::Yes));
WrapInParens([&]() {
mOutputFormatHelper.AppendParameterList(constructorDecl.parameters(), OutputFormatHelper::NameOnly::Yes);
});
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const CXXMemberCallExpr* stmt)
{
LAMBDA_SCOPE_HELPER(MemberCallExpr);
InsertArg(stmt->getCallee());
WrapInParens([&]() { ForEachArg(stmt->arguments(), [&](const auto& arg) { InsertArg(arg); }); });
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const ParenExpr* stmt)
{
WrapInParens([&]() { InsertArg(stmt->getSubExpr()); });
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const UnaryOperator* stmt)
{
const StringRef opCodeName = UnaryOperator::getOpcodeStr(stmt->getOpcode());
const bool insertBefore{!stmt->isPostfix()};
if(insertBefore) {
mOutputFormatHelper.Append(opCodeName);
}
InsertArg(stmt->getSubExpr());
if(!insertBefore) {
mOutputFormatHelper.Append(opCodeName);
}
}
//------------- ----------------------------------------------------------------
void CodeGenerator::InsertArg(const StringLiteral* stmt)
{
std::string data{};
llvm::raw_string_ostream stream{data};
stmt->outputString(stream);
mOutputFormatHelper.Append(stream.str());
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const ArrayInitIndexExpr* stmt)
{
Error(stmt, "ArrayInitIndexExpr should not be reached in CodeGenerator");
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const ArraySubscriptExpr* stmt)
{
if((not GetInsightsOptions().UseAltArraySubscriptionSyntax) || stmt->getLHS()->isLValue()) {
InsertArg(stmt->getLHS());
mOutputFormatHelper.Append('[');
InsertArg(stmt->getRHS());
mOutputFormatHelper.Append(']');
} else {
mOutputFormatHelper.Append("(*(");
InsertArg(stmt->getLHS());
mOutputFormatHelper.Append(" + ");
InsertArg(stmt->getRHS());
mOutputFormatHelper.Append("))");
}
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const ArrayInitLoopExpr* stmt)
{
WrapInCurlys([&]() {
const uint64_t size = stmt->getArraySize().getZExtValue();
ForEachArg(NumberIterator(size), [&](const auto& i) {
ArrayInitCodeGenerator codeGenerator{mOutputFormatHelper, i};
codeGenerator.InsertArg(stmt->getSubExpr());
});
});
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const OpaqueValueExpr* stmt)
{
InsertArg(stmt->getSourceExpr());
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const CallExpr* stmt)
{
LAMBDA_SCOPE_HELPER(CallExpr);
InsertArg(stmt->getCallee());
if(isa<UserDefinedLiteral>(stmt)) {
if(const auto* declRefExpr = cast<DeclRefExpr>(stmt->getCallee()->IgnoreImpCasts())) {
if(const TemplateArgumentList* args =
cast<FunctionDecl>(declRefExpr->getDecl())->getTemplateSpecializationArgs()) {
if(1 != args->size()) {
InsertTemplateArgs(args->asArray());
} else {
mOutputFormatHelper.Append('<');
const TemplateArgument& pack = args->get(0);
ForEachArg(pack.pack_elements(), [&](const auto& arg) {
const char c{static_cast<char>(arg.getAsIntegral().getZExtValue())};
mOutputFormatHelper.Append("'", std::string{c}, "'");
});
mOutputFormatHelper.Append('>');
}
}
}
}
WrapInParens([&]() { ForEachArg(stmt->arguments(), [&](const auto& arg) { InsertArg(arg); }); });
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const CXXNamedCastExpr* stmt)
{
const QualType castDestType = stmt->getTypeAsWritten();
const Expr* subExpr = stmt->getSubExpr();
FormatCast(stmt->getCastName(), castDestType, subExpr, stmt->getCastKind());
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const ImplicitCastExpr* stmt)
{
const Expr* subExpr = stmt->getSubExpr();
const auto castKind = stmt->getCastKind();
if(!clang::ast_matchers::IsMatchingCast(castKind)) {
InsertArg(subExpr);
} else if(isa<IntegerLiteral>(subExpr) && not GetInsightsOptions().ShowAllImplicitCasts) {
InsertArg(stmt->IgnoreCasts());
} else {
static const std::string castName{GetCastName(castKind)};
const QualType castDestType{stmt->getType().getCanonicalType()};
FormatCast(castName, castDestType, subExpr, castKind);
}
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const DeclRefExpr* stmt)
{
const auto* ctx = stmt->getDecl()->getDeclContext();
if(!ctx->isFunctionOrMethod()) {
ParseDeclContext(ctx);
mOutputFormatHelper.Append(GetPlainName(*stmt));
} else {
mOutputFormatHelper.Append(GetName(*stmt));
}
InsertTemplateArgs(*stmt);
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const CompoundStmt* stmt)
{
mOutputFormatHelper.OpenScope();
HandleCompoundStmt(stmt);
mOutputFormatHelper.CloseScope(OutputFormatHelper::NoNewLineBefore::Yes);
}
//-----------------------------------------------------------------------------
template<typename... Args>
static bool IsStmtRequieringSemi(const Stmt* stmt)
{
return (... && !isa<Args>(stmt));
}
//-----------------------------------------------------------------------------
void CodeGenerator::HandleCompoundStmt(const CompoundStmt* stmt)
{
for(const auto* item : stmt->body()) {
InsertArg(item);
if(IsStmtRequieringSemi<IfStmt, ForStmt, DeclStmt, WhileStmt, DoStmt, CXXForRangeStmt, SwitchStmt>(item)) {
mOutputFormatHelper.AppendSemiNewLine();
}
}
}
//-----------------------------------------------------------------------------
void CodeGenerator::InsertArg(const IfStmt* stmt)
{
const std::string cexpr{stmt->isConstexpr() ? kwSpaceConstExpr : ""};
const bool hasInit{stmt->getInit() || stmt->getConditionVariable()};
if(hasInit) {
mOutputFormatHelper.OpenScope();
if(const auto* conditionVar = stmt->getConditionVariable()) {
InsertArg(conditionVar);