forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDemangler.cpp
2022 lines (1854 loc) · 66 KB
/
Demangler.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
//===--- Demangler.cpp - String to Node-Tree Demangling -------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements new Swift de-mangler.
//
//===----------------------------------------------------------------------===//
#include "swift/Basic/Demangler.h"
#include "swift/Basic/ManglingUtils.h"
#include "swift/Basic/ManglingMacros.h"
#include "swift/Basic/Punycode.h"
#include "swift/Basic/Range.h"
#include "swift/Strings.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Compiler.h"
using namespace swift;
using namespace NewMangling;
using swift::Demangle::FunctionSigSpecializationParamKind;
//////////////////////////////////
// Private utility functions //
//////////////////////////////////
[[noreturn]]
static void demangler_unreachable(const char *Message) {
fprintf(stderr, "fatal error: %s\n", Message);
std::abort();
}
namespace {
static bool isDeclName(Node::Kind kind) {
switch (kind) {
case Node::Kind::Identifier:
case Node::Kind::LocalDeclName:
case Node::Kind::PrivateDeclName:
case Node::Kind::PrefixOperator:
case Node::Kind::PostfixOperator:
case Node::Kind::InfixOperator:
return true;
default:
return false;
}
}
static bool isContext(Node::Kind kind) {
switch (kind) {
#define NODE(ID)
#define CONTEXT_NODE(ID) \
case Node::Kind::ID:
#include "swift/Basic/DemangleNodes.def"
return true;
default:
return false;
}
}
static bool isNominal(Node::Kind kind) {
switch (kind) {
case Node::Kind::Structure:
case Node::Kind::Class:
case Node::Kind::Enum:
case Node::Kind::Protocol:
return true;
default:
return false;
}
}
static bool isEntity(Node::Kind kind) {
// Also accepts some kind which are not entities.
if (kind == Node::Kind::Type)
return true;
return isContext(kind);
}
static bool isRequirement(Node::Kind kind) {
switch (kind) {
case Node::Kind::DependentGenericSameTypeRequirement:
case Node::Kind::DependentGenericLayoutRequirement:
case Node::Kind::DependentGenericConformanceRequirement:
return true;
default:
return false;
}
}
static bool isFunctionAttr(Node::Kind kind) {
switch (kind) {
case Node::Kind::FunctionSignatureSpecialization:
case Node::Kind::GenericSpecialization:
case Node::Kind::GenericSpecializationNotReAbstracted:
case Node::Kind::GenericPartialSpecialization:
case Node::Kind::GenericPartialSpecializationNotReAbstracted:
case Node::Kind::ObjCAttribute:
case Node::Kind::NonObjCAttribute:
case Node::Kind::DynamicAttribute:
case Node::Kind::DirectMethodReferenceAttribute:
case Node::Kind::VTableAttribute:
case Node::Kind::PartialApplyForwarder:
case Node::Kind::PartialApplyObjCForwarder:
return true;
default:
return false;
}
}
} // anonymous namespace
namespace swift {
namespace Demangle {
//////////////////////////////////
// Context member functions //
//////////////////////////////////
Context::Context() : D(new Demangler) {
}
Context::~Context() {
delete D;
}
void Context::clear() {
D->clear();
}
NodePointer Context::demangleSymbolAsNode(llvm::StringRef MangledName) {
#ifndef NO_NEW_DEMANGLING
if (MangledName.startswith(MANGLING_PREFIX_STR)) {
return D->demangleSymbol(MangledName);
}
#endif
return demangleOldSymbolAsNode(MangledName, *D);
}
NodePointer Context::demangleTypeAsNode(llvm::StringRef MangledName) {
return D->demangleType(MangledName);
}
std::string Context::demangleSymbolAsString(llvm::StringRef MangledName,
const DemangleOptions &Options) {
NodePointer root = demangleSymbolAsNode(MangledName);
if (!root) return MangledName.str();
std::string demangling = nodeToString(root, Options);
if (demangling.empty())
return MangledName.str();
return demangling;
}
std::string Context::demangleTypeAsString(llvm::StringRef MangledName,
const DemangleOptions &Options) {
NodePointer root = demangleTypeAsNode(MangledName);
if (!root) return MangledName.str();
std::string demangling = nodeToString(root, Options);
if (demangling.empty())
return MangledName.str();
return demangling;
}
bool Context::isThunkSymbol(llvm::StringRef MangledName) {
if (MangledName.startswith(MANGLING_PREFIX_STR)) {
// First do a quick check
if (MangledName.endswith("TA") || // partial application forwarder
MangledName.endswith("Ta") || // ObjC partial application forwarder
MangledName.endswith("To") || // swift-as-ObjC thunk
MangledName.endswith("TO")) { // ObjC-as-swift thunk
// To avoid false positives, we need to fully demangle the symbol.
NodePointer Nd = D->demangleSymbol(MangledName);
if (!Nd || Nd->getKind() != Node::Kind::Global ||
Nd->getNumChildren() == 0)
return false;
switch (Nd->getFirstChild()->getKind()) {
case Node::Kind::ObjCAttribute:
case Node::Kind::NonObjCAttribute:
case Node::Kind::PartialApplyObjCForwarder:
case Node::Kind::PartialApplyForwarder:
return true;
default:
break;
}
}
return false;
}
if (MangledName.startswith("_T")) {
// Old mangling.
StringRef Remaining = MangledName.substr(2);
if (Remaining.startswith("To") || // swift-as-ObjC thunk
Remaining.startswith("TO") || // ObjC-as-swift thunk
Remaining.startswith("PA")) { // (ObjC) partial application forwarder
return true;
}
}
return false;
}
NodePointer Context::createNode(Node::Kind K) {
return D->createNode(K);
}
NodePointer Context::createNode(Node::Kind K, Node::IndexType Index) {
return D->createNode(K, Index);
}
NodePointer Context::createNode(Node::Kind K, llvm::StringRef Text) {
return D->createNode(K, Text);
}
//////////////////////////////////
// Public utility functions //
//////////////////////////////////
std::string demangleSymbolAsString(const char *MangledName,
size_t MangledNameLength,
const DemangleOptions &Options) {
Context Ctx;
return Ctx.demangleSymbolAsString(StringRef(MangledName, MangledNameLength),
Options);
}
std::string demangleTypeAsString(const char *MangledName,
size_t MangledNameLength,
const DemangleOptions &Options) {
Context Ctx;
return Ctx.demangleTypeAsString(StringRef(MangledName, MangledNameLength),
Options);
}
//////////////////////////////////
// Node member functions //
//////////////////////////////////
void Node::addChild(NodePointer Child, NodeFactory &Factory) {
assert(Child && "adding null child!");
if (NumChildren >= ReservedChildren)
Factory.Reallocate(Children, ReservedChildren, 1);
assert(NumChildren < ReservedChildren);
Children[NumChildren++] = Child;
}
void Node::addChild(NodePointer Child, Context &Ctx) {
addChild(Child, *Ctx.D);
}
//////////////////////////////////
// NodeFactory member functions //
//////////////////////////////////
void NodeFactory::freeSlabs(Slab *slab) {
while (slab) {
Slab *prev = slab->Previous;
#ifdef NODE_FACTORY_DEBUGGING
std::cerr << " free slab = " << slab << "\n";
#endif
free(slab);
slab = prev;
}
}
void NodeFactory::clear() {
if (CurrentSlab) {
freeSlabs(CurrentSlab->Previous);
// Recycle the last allocated slab.
// Note that the size of the last slab is at least as big as all previous
// slabs combined. Therefore it's not worth the effort of reusing all slabs.
// The slab size also stays the same. So at some point the demangling
// process converges to a single large slab across repeated demangle-clear
// cycles.
CurrentSlab->Previous = nullptr;
CurPtr = (char *)(CurrentSlab + 1);
assert(End == CurPtr + SlabSize);
}
}
NodePointer NodeFactory::createNode(Node::Kind K) {
return new (Allocate<Node>()) Node(K);
}
NodePointer NodeFactory::createNode(Node::Kind K, Node::IndexType Index) {
return new (Allocate<Node>()) Node(K, Index);
}
NodePointer NodeFactory::createNode(Node::Kind K, llvm::StringRef Text) {
return new (Allocate<Node>()) Node(K, Text.copy(*this));
}
NodePointer NodeFactory::createNode(Node::Kind K, const char *Text) {
return new (Allocate<Node>()) Node(K, llvm::StringRef(Text));
}
//////////////////////////////////
// Demangler member functions //
//////////////////////////////////
void Demangler::init(StringRef MangledName) {
NodeStack.clear();
Substitutions.clear();
PendingSubstitutions.clear();
NumWords = 0;
Text = MangledName;
Pos = 0;
}
NodePointer Demangler::demangleSymbol(StringRef MangledName) {
init(MangledName);
if (!nextIf(MANGLING_PREFIX_STR))
return nullptr;
NodePointer topLevel = createNode(Node::Kind::Global);
parseAndPushNodes();
// Let a trailing '_' be part of the not demangled suffix.
popNode(Node::Kind::FirstElementMarker);
size_t EndPos = (NodeStack.empty() ? 0 : NodeStack.back().Pos);
NodePointer Parent = topLevel;
while (NodePointer FuncAttr = popNode(isFunctionAttr)) {
Parent->addChild(FuncAttr, *this);
if (FuncAttr->getKind() == Node::Kind::PartialApplyForwarder ||
FuncAttr->getKind() == Node::Kind::PartialApplyObjCForwarder)
Parent = FuncAttr;
}
for (const NodeWithPos &NWP : NodeStack) {
NodePointer Nd = NWP.Node;
switch (Nd->getKind()) {
case Node::Kind::Type:
Parent->addChild(Nd->getFirstChild(), *this);
break;
case Node::Kind::Identifier:
if (StringRef(Nd->getText()).startswith("_T")) {
NodePointer Global = demangleOldSymbolAsNode(Nd->getText(), *this);
if (Global && Global->getKind() == Node::Kind::Global) {
for (NodePointer Child : *Global) {
Parent->addChild(Child, *this);
}
break;
}
}
LLVM_FALLTHROUGH;
default:
Parent->addChild(Nd, *this);
break;
}
}
if (EndPos < Text.size()) {
topLevel->addChild(createNode(Node::Kind::Suffix, Text.substr(EndPos)), *this);
}
return topLevel;
}
NodePointer Demangler::demangleType(StringRef MangledName) {
init(MangledName);
parseAndPushNodes();
if (NodePointer Result = popNode())
return Result;
return createNode(Node::Kind::Suffix, Text);
}
void Demangler::parseAndPushNodes() {
int Idx = 0;
while (!Text.empty()) {
NodePointer Node = demangleOperator();
if (!Node)
break;
pushNode(Node);
Idx++;
}
}
NodePointer Demangler::addChild(NodePointer Parent, NodePointer Child) {
if (!Parent || !Child)
return nullptr;
Parent->addChild(Child, *this);
return Parent;
}
NodePointer Demangler::createWithChild(Node::Kind kind,
NodePointer Child) {
if (!Child)
return nullptr;
NodePointer Nd = createNode(kind);
Nd->addChild(Child, *this);
return Nd;
}
NodePointer Demangler::createType(NodePointer Child) {
return createWithChild(Node::Kind::Type, Child);
}
NodePointer Demangler::Demangler::createWithChildren(Node::Kind kind,
NodePointer Child1, NodePointer Child2) {
if (!Child1 || !Child2)
return nullptr;
NodePointer Nd = createNode(kind);
Nd->addChild(Child1, *this);
Nd->addChild(Child2, *this);
return Nd;
}
NodePointer Demangler::createWithChildren(Node::Kind kind,
NodePointer Child1,
NodePointer Child2,
NodePointer Child3) {
if (!Child1 || !Child2 || !Child3)
return nullptr;
NodePointer Nd = createNode(kind);
Nd->addChild(Child1, *this);
Nd->addChild(Child2, *this);
Nd->addChild(Child3, *this);
return Nd;
}
NodePointer Demangler::changeKind(NodePointer Node, Node::Kind NewKind) {
if (!Node)
return nullptr;
NodePointer NewNode = nullptr;
if (Node->hasText()) {
NewNode = createNode(NewKind, Node->getText());
} else if (Node->hasIndex()) {
NewNode = createNode(NewKind, Node->getIndex());
} else {
NewNode = createNode(NewKind);
}
for (NodePointer Child : *Node) {
NewNode->addChild(Child, *this);
}
return NewNode;
}
NodePointer Demangler::demangleOperator() {
switch (char c = nextChar()) {
case 'A': return demangleMultiSubstitutions();
case 'B': return demangleBuiltinType();
case 'C': return demangleNominalType(Node::Kind::Class);
case 'D': return createWithChild(Node::Kind::TypeMangling,
popNode(Node::Kind::Type));
case 'E': return demangleExtensionContext();
case 'F': return demanglePlainFunction();
case 'G': return demangleBoundGenericType();
case 'I': return demangleImplFunctionType();
case 'K': return createNode(Node::Kind::ThrowsAnnotation);
case 'L': return demangleLocalIdentifier();
case 'M': return demangleMetatype();
case 'N': return createWithChild(Node::Kind::TypeMetadata,
popNode(Node::Kind::Type));
case 'O': return demangleNominalType(Node::Kind::Enum);
case 'P': return demangleNominalType(Node::Kind::Protocol);
case 'Q': return demangleArchetype();
case 'R': return demangleGenericRequirement();
case 'S': return demangleKnownType();
case 'T': return demangleThunkOrSpecialization();
case 'V': return demangleNominalType(Node::Kind::Structure);
case 'W': return demangleWitness();
case 'X': return demangleSpecialType();
case 'Z': return createWithChild(Node::Kind::Static, popNode(isEntity));
case 'a': return demangleTypeAlias();
case 'c': return popFunctionType(Node::Kind::FunctionType);
case 'd': return createNode(Node::Kind::VariadicMarker);
case 'f': return demangleFunctionEntity();
case 'i': return demangleEntity(Node::Kind::Subscript);
case 'l': return demangleGenericSignature(/*hasParamCounts*/ false);
case 'm': return createType(createWithChild(Node::Kind::Metatype,
popNode(Node::Kind::Type)));
case 'o': return demangleOperatorIdentifier();
case 'p': return demangleProtocolListType();
case 'q': return createType(demangleGenericParamIndex());
case 'r': return demangleGenericSignature(/*hasParamCounts*/ true);
case 's': return createNode(Node::Kind::Module, STDLIB_NAME);
case 't': return popTuple();
case 'u': return demangleGenericType();
case 'v': return demangleEntity(Node::Kind::Variable);
case 'w': return demangleValueWitness();
case 'x': return createType(getDependentGenericParamType(0, 0));
case 'y': return createNode(Node::Kind::EmptyList);
case 'z': return createType(createWithChild(Node::Kind::InOut,
popTypeAndGetChild()));
case '_': return createNode(Node::Kind::FirstElementMarker);
default:
pushBack();
return demangleIdentifier();
}
}
int Demangler::demangleNatural() {
if (!isDigit(peekChar()))
return -1000;
int num = 0;
while (true) {
char c = peekChar();
if (!isDigit(c))
return num;
int newNum = (10 * num) + (c - '0');
if (newNum < num)
return -1000;
num = newNum;
nextChar();
}
}
int Demangler::demangleIndex() {
if (nextIf('_'))
return 0;
int num = demangleNatural();
if (num >= 0 && nextIf('_'))
return num + 1;
return -1000;
}
NodePointer Demangler::demangleIndexAsNode() {
int Idx = demangleIndex();
if (Idx >= 0)
return createNode(Node::Kind::Number, Idx);
return nullptr;
}
NodePointer Demangler::demangleMultiSubstitutions() {
while (true) {
char c = nextChar();
if (isLowerLetter(c)) {
unsigned Idx = c - 'a';
if (Idx >= Substitutions.size())
return nullptr;
pushNode(Substitutions[Idx]);
continue;
}
if (isUpperLetter(c)) {
unsigned Idx = c - 'A';
if (Idx >= Substitutions.size())
return nullptr;
return Substitutions[Idx];
}
pushBack();
unsigned Idx = demangleIndex() + 26;
if (Idx >= Substitutions.size())
return nullptr;
return Substitutions[Idx];
}
}
NodePointer Demangler::createSwiftType(Node::Kind typeKind, StringRef name) {
return createType(createWithChildren(typeKind,
createNode(Node::Kind::Module, STDLIB_NAME),
createNode(Node::Kind::Identifier, name)));
}
NodePointer Demangler::demangleKnownType() {
switch (nextChar()) {
case 'o':
return createNode(Node::Kind::Module, MANGLING_MODULE_OBJC);
case 'C':
return createNode(Node::Kind::Module, MANGLING_MODULE_C);
case 'a':
return createSwiftType(Node::Kind::Structure, "Array");
case 'b':
return createSwiftType(Node::Kind::Structure, "Bool");
case 'c':
return createSwiftType(Node::Kind::Structure, "UnicodeScalar");
case 'd':
return createSwiftType(Node::Kind::Structure, "Double");
case 'f':
return createSwiftType(Node::Kind::Structure, "Float");
case 'i':
return createSwiftType(Node::Kind::Structure, "Int");
case 'V':
return createSwiftType(Node::Kind::Structure, "UnsafeRawPointer");
case 'v':
return createSwiftType(Node::Kind::Structure, "UnsafeMutableRawPointer");
case 'P':
return createSwiftType(Node::Kind::Structure, "UnsafePointer");
case 'p':
return createSwiftType(Node::Kind::Structure, "UnsafeMutablePointer");
case 'q':
return createSwiftType(Node::Kind::Enum, "Optional");
case 'Q':
return createSwiftType(Node::Kind::Enum, "ImplicitlyUnwrappedOptional");
case 'R':
return createSwiftType(Node::Kind::Structure, "UnsafeBufferPointer");
case 'r':
return createSwiftType(Node::Kind::Structure, "UnsafeMutableBufferPointer");
case 'S':
return createSwiftType(Node::Kind::Structure, "String");
case 'u':
return createSwiftType(Node::Kind::Structure, "UInt");
case 'g':
return createType(createWithChildren(Node::Kind::BoundGenericEnum,
createSwiftType(Node::Kind::Enum, "Optional"),
createWithChild(Node::Kind::TypeList, popNode(Node::Kind::Type))));
default:
return nullptr;
}
}
NodePointer Demangler::demangleIdentifier() {
bool hasWordSubsts = false;
bool isPunycoded = false;
char c = peekChar();
if (!isDigit(c))
return nullptr;
if (c == '0') {
nextChar();
if (peekChar() == '0') {
nextChar();
isPunycoded = true;
} else {
hasWordSubsts = true;
}
}
std::string Identifier;
do {
while (hasWordSubsts && isLetter(peekChar())) {
char c = nextChar();
int WordIdx = 0;
if (isLowerLetter(c)) {
WordIdx = c - 'a';
} else {
assert(isUpperLetter(c));
WordIdx = c - 'A';
hasWordSubsts = false;
}
if (WordIdx >= NumWords)
return nullptr;
assert(WordIdx < MaxNumWords);
StringRef Slice = Words[WordIdx];
Identifier.append(Slice.data(), Slice.size());
}
if (nextIf('0'))
break;
int numChars = demangleNatural();
if (numChars <= 0)
return nullptr;
if (isPunycoded)
nextIf('_');
if (Pos + numChars > Text.size())
return nullptr;
StringRef Slice = StringRef(Text.data() + Pos, numChars);
if (isPunycoded) {
if (!Punycode::decodePunycodeUTF8(Slice, Identifier))
return nullptr;
} else {
Identifier.append(Slice.data(), Slice.size());
int wordStartPos = -1;
for (int Idx = 0, End = (int)Slice.size(); Idx <= End; ++Idx) {
char c = (Idx < End ? Slice[Idx] : 0);
if (wordStartPos >= 0 && isWordEnd(c, Slice[Idx - 1])) {
if (Idx - wordStartPos >= 2 && NumWords < MaxNumWords) {
StringRef word(Slice.begin() + wordStartPos, Idx - wordStartPos);
Words[NumWords++] = word;
}
wordStartPos = -1;
}
if (wordStartPos < 0 && isWordStart(c)) {
wordStartPos = Idx;
}
}
}
Pos += numChars;
} while (hasWordSubsts);
if (Identifier.empty())
return nullptr;
NodePointer Ident = createNode(Node::Kind::Identifier, Identifier);
addSubstitution(Ident);
return Ident;
}
NodePointer Demangler::demangleOperatorIdentifier() {
NodePointer Ident = popNode(Node::Kind::Identifier);
static const char op_char_table[] = "& @/= > <*!|+?%-~ ^ .";
std::string OpStr;
OpStr.reserve(Ident->getText().size());
for (signed char c : Ident->getText()) {
if (c < 0) {
// Pass through Unicode characters.
OpStr.push_back(c);
continue;
}
if (!isLowerLetter(c))
return nullptr;
char o = op_char_table[c - 'a'];
if (o == ' ')
return nullptr;
OpStr.push_back(o);
}
switch (nextChar()) {
case 'i': return createNode(Node::Kind::InfixOperator, OpStr);
case 'p': return createNode(Node::Kind::PrefixOperator, OpStr);
case 'P': return createNode(Node::Kind::PostfixOperator, OpStr);
default: return nullptr;
}
}
NodePointer Demangler::demangleLocalIdentifier() {
if (nextIf('L')) {
NodePointer discriminator = popNode(Node::Kind::Identifier);
NodePointer name = popNode(isDeclName);
return createWithChildren(Node::Kind::PrivateDeclName, discriminator, name);
}
NodePointer discriminator = demangleIndexAsNode();
NodePointer name = popNode(isDeclName);
return createWithChildren(Node::Kind::LocalDeclName, discriminator, name);
}
NodePointer Demangler::popModule() {
if (NodePointer Ident = popNode(Node::Kind::Identifier))
return changeKind(Ident, Node::Kind::Module);
return popNode(Node::Kind::Module);
}
NodePointer Demangler::popContext() {
if (NodePointer Mod = popModule())
return Mod;
if (NodePointer Ty = popNode(Node::Kind::Type)) {
if (Ty->getNumChildren() != 1)
return nullptr;
NodePointer Child = Ty->getFirstChild();
if (!isContext(Child->getKind()))
return nullptr;
return Child;
}
return popNode(isContext);
}
NodePointer Demangler::popTypeAndGetChild() {
NodePointer Ty = popNode(Node::Kind::Type);
if (!Ty || Ty->getNumChildren() != 1)
return nullptr;
return Ty->getFirstChild();
}
NodePointer Demangler::popTypeAndGetNominal() {
NodePointer Child = popTypeAndGetChild();
if (Child && isNominal(Child->getKind()))
return Child;
return nullptr;
}
NodePointer Demangler::demangleBuiltinType() {
NodePointer Ty = nullptr;
switch (nextChar()) {
case 'b':
Ty = createNode(Node::Kind::BuiltinTypeName,
"Builtin.BridgeObject");
break;
case 'B':
Ty = createNode(Node::Kind::BuiltinTypeName,
"Builtin.UnsafeValueBuffer");
break;
case 'f': {
int size = demangleIndex() - 1;
if (size <= 0)
return nullptr;
Ty = createNode(Node::Kind::BuiltinTypeName,
std::move(DemanglerPrinter() << "Builtin.Float" << size).str());
break;
}
case 'i': {
int size = demangleIndex() - 1;
if (size <= 0)
return nullptr;
Ty = createNode(Node::Kind::BuiltinTypeName,
(DemanglerPrinter() << "Builtin.Int" << size).str());
break;
}
case 'v': {
int elts = demangleIndex() - 1;
if (elts <= 0)
return nullptr;
NodePointer EltType = popTypeAndGetChild();
if (!EltType || EltType->getKind() != Node::Kind::BuiltinTypeName ||
!EltType->getText().startswith("Builtin."))
return nullptr;
Ty = createNode(Node::Kind::BuiltinTypeName,
(DemanglerPrinter() << "Builtin.Vec" << elts << "x" <<
EltType->getText().substr(sizeof("Builtin.") - 1)).str());
break;
}
case 'O':
Ty = createNode(Node::Kind::BuiltinTypeName,
"Builtin.UnknownObject");
break;
case 'o':
Ty = createNode(Node::Kind::BuiltinTypeName,
"Builtin.NativeObject");
break;
case 'p':
Ty = createNode(Node::Kind::BuiltinTypeName,
"Builtin.RawPointer");
break;
case 'w':
Ty = createNode(Node::Kind::BuiltinTypeName,
"Builtin.Word");
break;
default:
return nullptr;
}
return createType(Ty);
}
NodePointer Demangler::demangleNominalType(Node::Kind kind) {
NodePointer Name = popNode(isDeclName);
NodePointer Ctx = popContext();
NodePointer NTy = createType(createWithChildren(kind, Ctx, Name));
addSubstitution(NTy);
return NTy;
}
NodePointer Demangler::demangleTypeAlias() {
NodePointer Name = popNode(isDeclName);
NodePointer Ctx = popContext();
return createType(createWithChildren(Node::Kind::TypeAlias, Ctx, Name));
}
NodePointer Demangler::demangleExtensionContext() {
NodePointer GenSig = popNode(Node::Kind::DependentGenericSignature);
NodePointer Module = popModule();
NodePointer Type = popTypeAndGetNominal();
NodePointer Ext = createWithChildren(Node::Kind::Extension, Module, Type);
if (GenSig)
Ext = addChild(Ext, GenSig);
return Ext;
}
NodePointer Demangler::demanglePlainFunction() {
NodePointer GenSig = popNode(Node::Kind::DependentGenericSignature);
NodePointer Type = popFunctionType(Node::Kind::FunctionType);
if (GenSig) {
Type = createType(createWithChildren(Node::Kind::DependentGenericType,
GenSig, Type));
}
NodePointer Name = popNode(isDeclName);
NodePointer Ctx = popContext();
return createWithChildren(Node::Kind::Function, Ctx, Name, Type);
}
NodePointer Demangler::popFunctionType(Node::Kind kind) {
NodePointer FuncType = createNode(kind);
addChild(FuncType, popNode(Node::Kind::ThrowsAnnotation));
FuncType = addChild(FuncType, popFunctionParams(Node::Kind::ArgumentTuple));
FuncType = addChild(FuncType, popFunctionParams(Node::Kind::ReturnType));
return createType(FuncType);
}
NodePointer Demangler::popFunctionParams(Node::Kind kind) {
NodePointer ParamsType = nullptr;
if (popNode(Node::Kind::EmptyList)) {
ParamsType = createType(createNode(Node::Kind::NonVariadicTuple));
} else {
ParamsType = popNode(Node::Kind::Type);
}
return createWithChild(kind, ParamsType);
}
NodePointer Demangler::popTuple() {
NodePointer Root = createNode(popNode(Node::Kind::VariadicMarker) ?
Node::Kind::VariadicTuple :
Node::Kind::NonVariadicTuple);
if (!popNode(Node::Kind::EmptyList)) {
std::vector<NodePointer> Nodes;
bool firstElem = false;
do {
firstElem = (popNode(Node::Kind::FirstElementMarker) != nullptr);
NodePointer TupleElmt = createNode(Node::Kind::TupleElement);
if (NodePointer Ident = popNode(Node::Kind::Identifier)) {
TupleElmt->addChild(createNode(Node::Kind::TupleElementName,
Ident->getText()), *this);
}
NodePointer Ty = popNode(Node::Kind::Type);
if (!Ty)
return nullptr;
TupleElmt->addChild(Ty, *this);
Nodes.push_back(TupleElmt);
} while (!firstElem);
while (NodePointer TupleElmt = pop_back_val(Nodes)) {
Root->addChild(TupleElmt, *this);
}
}
return createType(Root);
}
NodePointer Demangler::popTypeList() {
NodePointer Root = createNode(Node::Kind::TypeList);
if (!popNode(Node::Kind::EmptyList)) {
std::vector<NodePointer> Nodes;
bool firstElem = false;
do {
firstElem = (popNode(Node::Kind::FirstElementMarker) != nullptr);
NodePointer Ty = popNode(Node::Kind::Type);
if (!Ty)
return nullptr;
Nodes.push_back(Ty);
} while (!firstElem);
while (NodePointer Ty = pop_back_val(Nodes)) {
Root->addChild(Ty, *this);
}
}
return Root;
}
NodePointer Demangler::popProtocol() {
NodePointer Name = popNode(isDeclName);
NodePointer Ctx = popContext();
NodePointer Proto = createWithChildren(Node::Kind::Protocol, Ctx, Name);
return createType(Proto);
}
NodePointer Demangler::demangleBoundGenericType() {
std::vector<NodePointer> TypeListList;
std::vector<NodePointer> Types;
for (;;) {
NodePointer TList = createNode(Node::Kind::TypeList);
TypeListList.push_back(TList);
while (NodePointer Ty = popNode(Node::Kind::Type)) {
Types.push_back(Ty);
}
while (NodePointer Ty = pop_back_val(Types)) {
TList->addChild(Ty, *this);
}
if (popNode(Node::Kind::EmptyList))
break;
if (!popNode(Node::Kind::FirstElementMarker))
return nullptr;
}
NodePointer Nominal = popTypeAndGetNominal();
return createType(demangleBoundGenericArgs(Nominal, TypeListList, 0));
}
NodePointer Demangler::demangleBoundGenericArgs(NodePointer Nominal,
const std::vector<NodePointer> &TypeLists,
size_t TypeListIdx) {
if (!Nominal || Nominal->getNumChildren() < 2)
return nullptr;
if (TypeListIdx >= TypeLists.size())
return nullptr;
NodePointer args = TypeLists[TypeListIdx];
// Generic arguments for the outermost type come first.
NodePointer Context = Nominal->getFirstChild();
if (Context->getKind() != Node::Kind::Module &&
Context->getKind() != Node::Kind::Function &&
Context->getKind() != Node::Kind::Extension) {
NodePointer BoundParent = demangleBoundGenericArgs(Context, TypeLists,
TypeListIdx + 1);
// Rebuild this type with the new parent type, which may have
// had its generic arguments applied.
Nominal = createWithChildren(Nominal->getKind(), BoundParent,
Nominal->getChild(1));
if (!Nominal)
return nullptr;
}
// If there were no arguments at this level there is nothing left
// to do.
if (args->getNumChildren() == 0)
return Nominal;
Node::Kind kind;
switch (Nominal->getKind()) {
case Node::Kind::Class:
kind = Node::Kind::BoundGenericClass;
break;
case Node::Kind::Structure:
kind = Node::Kind::BoundGenericStructure;
break;
case Node::Kind::Enum:
kind = Node::Kind::BoundGenericEnum;
break;
default:
return nullptr;
}
return createWithChildren(kind, createType(Nominal), args);