-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathCwlDemangle.swift
More file actions
5105 lines (4743 loc) · 236 KB
/
CwlDemangle.swift
File metadata and controls
5105 lines (4743 loc) · 236 KB
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
//
// CwlDemangle.swift
// CwlDemangle
//
// Created by Matt Gallagher on 2017/11/17.
// Copyright © 2017 Matt Gallagher. All rights reserved.
//
import Foundation
/// This is likely to be the primary entry point to this file. Pass a string containing a Swift mangled symbol or type, get a parsed SwiftSymbol structure which can then be directly examined or printed.
///
/// - Parameters:
/// - mangled: the string to be parsed ("isType` is false, the string should start with a Swift Symbol prefix, _T, _$S or $S).
/// - isType: if true, no prefix is parsed and, on completion, the first item on the parse stack is returned.
/// - Returns: the successfully parsed result
/// - Throws: a SwiftSymbolParseError error that contains parse position when the error occurred.
public func parseMangledSwiftSymbol(_ mangled: String, isType: Bool = false) throws -> SwiftSymbol {
return try parseMangledSwiftSymbol(mangled.unicodeScalars, isType: isType)
}
/// Pass a collection of `UnicodeScalars` containing a Swift mangled symbol or type, get a parsed SwiftSymbol structure which can then be directly examined or printed.
///
/// - Parameters:
/// - mangled: the collection of `UnicodeScalars` to be parsed ("isType` is false, the string should start with a Swift Symbol prefix, _T, _$S or $S).
/// - isType: if true, no prefix is parsed and, on completion, the first item on the parse stack is returned.
/// - Returns: the successfully parsed result
/// - Throws: a SwiftSymbolParseError error that contains parse position when the error occurred.
public func parseMangledSwiftSymbol<C: Collection>(_ mangled: C, isType: Bool = false, symbolicReferenceResolver: ((Int32, Int) throws -> SwiftSymbol)? = nil) throws -> SwiftSymbol where C.Iterator.Element == UnicodeScalar {
var demangler = Demangler(scalars: mangled)
demangler.symbolicReferenceResolver = symbolicReferenceResolver
if isType {
return try demangler.demangleType()
} else if getManglingPrefixLength(mangled) != 0 {
return try demangler.demangleSymbol()
} else {
return try demangler.demangleSwift3TopLevelSymbol()
}
}
extension SwiftSymbol: CustomStringConvertible {
/// Overridden method to allow simple printing with default options
public var description: String {
var printer = SymbolPrinter()
_ = printer.printName(self)
return printer.target
}
/// Prints `SwiftSymbol`s to a String with the full set of printing options.
///
/// - Parameter options: an option set containing the different `DemangleOptions` from the Swift project.
/// - Returns: `self` printed to a string according to the specified options.
public func print(using options: SymbolPrintOptions = .default) -> String {
var printer = SymbolPrinter(options: options)
_ = printer.printName(self)
return printer.target
}
}
// MARK: Demangle.h
/// These options mimic those used in the Swift project. Check that project for details.
public struct SymbolPrintOptions: OptionSet {
public let rawValue: Int
public static let synthesizeSugarOnTypes = SymbolPrintOptions(rawValue: 1 << 0)
public static let displayDebuggerGeneratedModule = SymbolPrintOptions(rawValue: 1 << 1)
public static let qualifyEntities = SymbolPrintOptions(rawValue: 1 << 2)
public static let displayExtensionContexts = SymbolPrintOptions(rawValue: 1 << 3)
public static let displayUnmangledSuffix = SymbolPrintOptions(rawValue: 1 << 4)
public static let displayModuleNames = SymbolPrintOptions(rawValue: 1 << 5)
public static let displayGenericSpecializations = SymbolPrintOptions(rawValue: 1 << 6)
public static let displayProtocolConformances = SymbolPrintOptions(rawValue: 1 << 5)
public static let displayWhereClauses = SymbolPrintOptions(rawValue: 1 << 8)
public static let displayEntityTypes = SymbolPrintOptions(rawValue: 1 << 9)
public static let shortenPartialApply = SymbolPrintOptions(rawValue: 1 << 10)
public static let shortenThunk = SymbolPrintOptions(rawValue: 1 << 11)
public static let shortenValueWitness = SymbolPrintOptions(rawValue: 1 << 12)
public static let shortenArchetype = SymbolPrintOptions(rawValue: 1 << 13)
public static let showPrivateDiscriminators = SymbolPrintOptions(rawValue: 1 << 14)
public static let showFunctionArgumentTypes = SymbolPrintOptions(rawValue: 1 << 15)
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static let `default`: SymbolPrintOptions = [.displayDebuggerGeneratedModule, .qualifyEntities, .displayExtensionContexts, .displayUnmangledSuffix, .displayModuleNames, .displayGenericSpecializations, .displayProtocolConformances, .displayWhereClauses, .displayEntityTypes, .showPrivateDiscriminators, .showFunctionArgumentTypes]
public static let simplified: SymbolPrintOptions = [.synthesizeSugarOnTypes, .qualifyEntities, .shortenPartialApply, .shortenThunk, .shortenValueWitness, .shortenArchetype]
}
enum FunctionSigSpecializationParamKind: UInt64 {
case constantPropFunction = 0
case constantPropGlobal = 1
case constantPropInteger = 2
case constantPropFloat = 3
case constantPropString = 4
case closureProp = 5
case boxToValue = 6
case boxToStack = 7
case dead = 64
case ownedToGuaranteed = 128
case sroa = 256
case guaranteedToOwned = 512
case existentialToGeneric = 1024
}
enum SpecializationPass {
case allocBoxToStack
case closureSpecializer
case capturePromotion
case capturePropagation
case functionSignatureOpts
case genericSpecializer
}
enum Directness: UInt64, CustomStringConvertible {
case direct = 0
case indirect = 1
var description: String {
switch self {
case .direct: return "direct"
case .indirect: return "indirect"
}
}
}
enum DemangleFunctionEntityArgs {
case none, typeAndMaybePrivateName, typeAndIndex, index
}
enum DemangleGenericRequirementTypeKind {
case generic, assoc, compoundAssoc, substitution
}
enum DemangleGenericRequirementConstraintKind {
case `protocol`, baseClass, sameType, layout
}
enum ValueWitnessKind: UInt64, CustomStringConvertible {
case allocateBuffer = 0
case assignWithCopy = 1
case assignWithTake = 2
case deallocateBuffer = 3
case destroy = 4
case destroyArray = 5
case destroyBuffer = 6
case initializeBufferWithCopyOfBuffer = 7
case initializeBufferWithCopy = 8
case initializeWithCopy = 9
case initializeBufferWithTake = 10
case initializeWithTake = 11
case projectBuffer = 12
case initializeBufferWithTakeOfBuffer = 13
case initializeArrayWithCopy = 14
case initializeArrayWithTakeFrontToBack = 15
case initializeArrayWithTakeBackToFront = 16
case storeExtraInhabitant = 17
case getExtraInhabitantIndex = 18
case getEnumTag = 19
case destructiveProjectEnumData = 20
case destructiveInjectEnumTag = 21
case getEnumTagSinglePayload = 22
case storeEnumTagSinglePayload = 23
init?(code: String) {
switch code {
case "al": self = .allocateBuffer
case "ca": self = .assignWithCopy
case "ta": self = .assignWithTake
case "de": self = .deallocateBuffer
case "xx": self = .destroy
case "XX": self = .destroyBuffer
case "Xx": self = .destroyArray
case "CP": self = .initializeBufferWithCopyOfBuffer
case "Cp": self = .initializeBufferWithCopy
case "cp": self = .initializeWithCopy
case "Tk": self = .initializeBufferWithTake
case "tk": self = .initializeWithTake
case "pr": self = .projectBuffer
case "TK": self = .initializeBufferWithTakeOfBuffer
case "Cc": self = .initializeArrayWithCopy
case "Tt": self = .initializeArrayWithTakeFrontToBack
case "tT": self = .initializeArrayWithTakeBackToFront
case "xs": self = .storeExtraInhabitant
case "xg": self = .getExtraInhabitantIndex
case "ug": self = .getEnumTag
case "up": self = .destructiveProjectEnumData
case "ui": self = .destructiveInjectEnumTag
case "et": self = .getEnumTagSinglePayload
case "st": self = .storeEnumTagSinglePayload
default: return nil
}
}
var description: String {
switch self {
case .allocateBuffer: return "allocateBuffer"
case .assignWithCopy: return "assignWithCopy"
case .assignWithTake: return "assignWithTake"
case .deallocateBuffer: return "deallocateBuffer"
case .destroy: return "destroy"
case .destroyBuffer: return "destroyBuffer"
case .initializeBufferWithCopyOfBuffer: return "initializeBufferWithCopyOfBuffer"
case .initializeBufferWithCopy: return "initializeBufferWithCopy"
case .initializeWithCopy: return "initializeWithCopy"
case .initializeBufferWithTake: return "initializeBufferWithTake"
case .initializeWithTake: return "initializeWithTake"
case .projectBuffer: return "projectBuffer"
case .initializeBufferWithTakeOfBuffer: return "initializeBufferWithTakeOfBuffer"
case .destroyArray: return "destroyArray"
case .initializeArrayWithCopy: return "initializeArrayWithCopy"
case .initializeArrayWithTakeFrontToBack: return "initializeArrayWithTakeFrontToBack"
case .initializeArrayWithTakeBackToFront: return "initializeArrayWithTakeBackToFront"
case .storeExtraInhabitant: return "storeExtraInhabitant"
case .getExtraInhabitantIndex: return "getExtraInhabitantIndex"
case .getEnumTag: return "getEnumTag"
case .destructiveProjectEnumData: return "destructiveProjectEnumData"
case .destructiveInjectEnumTag: return "destructiveInjectEnumTag"
case .getEnumTagSinglePayload: return "getEnumTagSinglePayload"
case .storeEnumTagSinglePayload: return "storeEnumTagSinglePayload"
}
}
}
public struct SwiftSymbol {
public let kind: Kind
public var children: [SwiftSymbol]
public let contents: Contents
public enum Contents {
case none
case index(UInt64)
case name(String)
}
public init(kind: Kind, children: [SwiftSymbol] = [], contents: Contents = .none) {
self.kind = kind
self.children = children
self.contents = contents
}
fileprivate init(kind: Kind, child: SwiftSymbol) {
self.init(kind: kind, children: [child], contents: .none)
}
fileprivate init(typeWithChildKind: Kind, childChild: SwiftSymbol) {
self.init(kind: .type, children: [SwiftSymbol(kind: typeWithChildKind, children: [childChild])], contents: .none)
}
fileprivate init(typeWithChildKind: Kind, childChildren: [SwiftSymbol]) {
self.init(kind: .type, children: [SwiftSymbol(kind: typeWithChildKind, children: childChildren)], contents: .none)
}
fileprivate init(swiftStdlibTypeKind: Kind, name: String) {
self.init(kind: .type, children: [SwiftSymbol(kind: swiftStdlibTypeKind, children: [
SwiftSymbol(kind: .module, contents: .name(stdlibName)),
SwiftSymbol(kind: .identifier, contents: .name(name))
])], contents: .none)
}
fileprivate init(swiftBuiltinType: Kind, name: String) {
self.init(kind: .type, children: [SwiftSymbol(kind: swiftBuiltinType, contents: .name(name))])
}
fileprivate var text: String? {
switch contents {
case .name(let s): return s
default: return nil
}
}
fileprivate var index: UInt64? {
switch contents {
case .index(let i): return i
default: return nil
}
}
fileprivate var isProtocol: Bool {
switch kind {
case .type: return children.first?.isProtocol ?? false
case .protocol, .protocolSymbolicReference: return true
default: return false
}
}
fileprivate func changeChild(_ newChild: SwiftSymbol?, atIndex: Int) -> SwiftSymbol {
guard children.indices.contains(atIndex) else { return self }
var modifiedChildren = children
if let nc = newChild {
modifiedChildren[atIndex] = nc
} else {
modifiedChildren.remove(at: atIndex)
}
return SwiftSymbol(kind: kind, children: modifiedChildren, contents: contents)
}
fileprivate func changeKind(_ newKind: Kind, additionalChildren: [SwiftSymbol] = []) -> SwiftSymbol {
if case .name(let text) = contents {
return SwiftSymbol(kind: newKind, children: children + additionalChildren, contents: .name(text))
} else if case .index(let i) = contents {
return SwiftSymbol(kind: newKind, children: children + additionalChildren, contents: .index(i))
} else {
return SwiftSymbol(kind: newKind, children: children + additionalChildren, contents: .none)
}
}
}
// MARK: DemangleNodes.def
extension SwiftSymbol {
public enum Kind {
case `class`
case `enum`
case `extension`
case `protocol`
case protocolSymbolicReference
case `static`
case `subscript`
case allocator
case accessorFunctionaReference
case anonymousContext
case anonymousDescriptor
case anyProtocolConformanceList
case argumentTuple
case associatedConformanceDescriptor
case associatedType
case associatedTypeDescriptor
case associatedTypeGenericParamRef
case associatedTypeMetadataAccessor
case associatedTypeRef
case associatedTypeWitnessTableAccessor
case assocTypePath
case autoClosureType
case boundGenericClass
case boundGenericEnum
case boundGenericFunction
case boundGenericOtherNominalType
case boundGenericProtocol
case boundGenericStructure
case boundGenericTypeAlias
case builtinTypeName
case canonicalSpecializedGenericMetaclass
case canonicalSpecializedGenericTypeMetadataAccessFunction
case cFunctionPointer
case classMetadataBaseOffset
case concreteProtocolConformance
case constructor
case coroutineContinuationPrototype
case curryThunk
case deallocator
case declContext
case defaultArgumentInitializer
case defaultAssociatedConformanceAccessor
case defaultAssociatedTypeMetadataAccessor
case dependentAssociatedConformance
case dependentAssociatedTypeRef
case dependentGenericConformanceRequirement
case dependentGenericLayoutRequirement
case dependentGenericParamCount
case dependentGenericParamType
case dependentGenericSameTypeRequirement
case dependentGenericSignature
case dependentGenericType
case dependentMemberType
case dependentProtocolConformanceAssociated
case dependentProtocolConformanceInherited
case dependentProtocolConformanceRoot
case dependentPseudogenericSignature
case destructor
case didSet
case directMethodReferenceAttribute
case directness
case dispatchThunk
case dynamicAttribute
case dynamicSelf
case emptyList
case enumCase
case errorType
case escapingAutoClosureType
case existentialMetatype
case explicitClosure
case extensionDescriptor
case fieldOffset
case firstElementMarker
case fullTypeMetadata
case function
case functionSignatureSpecialization
case functionSignatureSpecializationParam
case functionSignatureSpecializationParamKind
case functionSignatureSpecializationParamPayload
case functionType
case genericPartialSpecialization
case genericPartialSpecializationNotReAbstracted
case genericProtocolWitnessTable
case genericProtocolWitnessTableInstantiationFunction
case genericSpecialization
case genericSpecializationNotReAbstracted
case genericSpecializationParam
case genericTypeMetadataPattern
case genericTypeParamDecl
case getter
case global
case globalGetter
case identifier
case implConvention
case implDifferentiability
case implDifferentiable
case implErrorResult
case implEscaping
case implFunctionAttribute
case implFunctionType
case implicitClosure
case implInvocationSubstitutions
case implLinear
case implParameter
case implPatternSubstitutions
case implResult
case implYield
case index
case infixOperator
case initializer
case inlinedGenericFunction
case inOut
case isSerialized
case iVarDestroyer
case iVarInitializer
case keyPathEqualsThunkHelper
case keyPathGetterThunkHelper
case keyPathHashThunkHelper
case keyPathSetterThunkHelper
case labelList
case lazyProtocolWitnessTableAccessor
case lazyProtocolWitnessTableCacheVariable
case localDeclName
case materializeForSet
case mergedFunction
case metaclass
case metatype
case metatypeRepresentation
case methodDescriptor
case methodLookupFunction
case modifyAccessor
case module
case moduleDescriptor
case nativeOwningAddressor
case nativeOwningMutableAddressor
case nativePinningAddressor
case nativePinningMutableAddressor
case noEscapeFunctionType
case nominalTypeDescriptor
case nonObjCAttribute
case number
case objCAttribute
case objCBlock
case opaqueReturnType
case opaqueReturnTypeOf
case opaqueType
case opaqueTypeDescriptor
case opaqueTypeDescriptorAccessor
case opaqueTypeDescriptorAccessorImpl
case opaqueTypeDescriptorAccessorKey
case opaqueTypeDescriptorAccessorVar
case opaqueTypeDescriptorSymbolicReference
case otherNominalType
case outlinedAssignWithCopy
case outlinedAssignWithTake
case outlinedBridgedMethod
case outlinedConsume
case outlinedCopy
case outlinedDestroy
case outlinedInitializeWithCopy
case outlinedInitializeWithTake
case outlinedRelease
case outlinedRetain
case outlinedVariable
case owned
case owningAddressor
case owningMutableAddressor
case partialApplyForwarder
case partialApplyObjCForwarder
case postfixOperator
case prefixOperator
case privateDeclName
case propertyDescriptor
case protocolConformance
case protocolConformanceRefInTypeModule
case protocolConformanceRefInProtocolModule
case protocolConformanceRefInOtherModule
case protocolConformanceDescriptor
case protocolDescriptor
case protocolList
case protocolListWithAnyObject
case protocolListWithClass
case protocolRequirementsBaseDescriptor
case protocolWitness
case protocolWitnessTable
case protocolWitnessTableAccessor
case protocolWitnessTablePattern
case reabstractionThunk
case reabstractionThunkHelper
case readAccessor
case reflectionMetadataAssocTypeDescriptor
case reflectionMetadataBuiltinDescriptor
case reflectionMetadataFieldDescriptor
case reflectionMetadataSuperclassDescriptor
case relatedEntityDeclName
case resilientProtocolWitnessTable
case retroactiveConformance
case returnType
case setter
case shared
case silBoxImmutableField
case silBoxLayout
case silBoxMutableField
case silBoxType
case silBoxTypeWithLayout
case specializationPassID
case structure
case suffix
case sugaredOptional
case sugaredArray
case sugaredDictionary
case sugaredParen
case typeSymbolicReference
case thinFunctionType
case throwsAnnotation
case tuple
case tupleElement
case tupleElementName
case type
case typeAlias
case typeList
case typeMangling
case typeMetadata
case typeMetadataAccessFunction
case typeMetadataCompletionFunction
case typeMetadataInstantiationCache
case typeMetadataInstantiationFunction
case typeMetadataLazyCache
case typeMetadataSingletonInitializationCache
case uncurriedFunctionType
case unknownIndex
case unmanaged
case unowned
case unsafeAddressor
case unsafeMutableAddressor
case valueWitness
case valueWitnessTable
case variable
case variadicMarker
case vTableAttribute // note: old mangling only
case vTableThunk
case weak
case willSet
}
}
// MARK: Demangler.h
fileprivate let stdlibName = "Swift"
fileprivate let objcModule = "__C"
fileprivate let cModule = "__C_Synthesized"
fileprivate let lldbExpressionsModuleNamePrefix = "__lldb_expr_"
fileprivate let maxRepeatCount = 2048
fileprivate let maxNumWords = 26
fileprivate struct Demangler<C> where C: Collection, C.Iterator.Element == UnicodeScalar {
var scanner: ScalarScanner<C>
var nameStack: [SwiftSymbol] = []
var substitutions: [SwiftSymbol] = []
var words: [String] = []
var symbolicReferences: [Int32] = []
var isOldFunctionTypeMangling: Bool = false
var symbolicReferenceResolver: ((Int32, Int) throws -> SwiftSymbol)? = nil
init(scalars: C) {
scanner = ScalarScanner(scalars: scalars)
}
}
// MARK: Demangler.cpp
fileprivate func getManglingPrefixLength<C: Collection>(_ scalars: C) -> Int where C.Iterator.Element == UnicodeScalar {
var scanner = ScalarScanner(scalars: scalars)
if scanner.conditional(string: "_T0") || scanner.conditional(string: "_$S") || scanner.conditional(string: "_$s") {
return 3
} else if scanner.conditional(string: "$S") || scanner.conditional(string: "$s") {
return 2
}
return 0
}
fileprivate extension SwiftSymbol.Kind {
var isDeclName: Bool {
switch self {
case .identifier, .localDeclName, .privateDeclName, .relatedEntityDeclName: fallthrough
case .prefixOperator, .postfixOperator, .infixOperator: fallthrough
case .typeSymbolicReference, .protocolSymbolicReference: return true
default: return false
}
}
var isContext: Bool {
switch self {
case .allocator, .anonymousContext, .class, .constructor, .curryThunk, .deallocator, .defaultArgumentInitializer: fallthrough
case .destructor, .didSet, .dispatchThunk, .enum, .explicitClosure, .extension, .function: fallthrough
case .getter, .globalGetter, .iVarInitializer, .iVarDestroyer, .implicitClosure: fallthrough
case .initializer, .materializeForSet, .module, .nativeOwningAddressor: fallthrough
case .nativeOwningMutableAddressor, .nativePinningAddressor, .nativePinningMutableAddressor: fallthrough
case .otherNominalType, .owningAddressor, .owningMutableAddressor, .protocol, .protocolSymbolicReference, .setter, .static: fallthrough
case .structure, .subscript, .typeSymbolicReference, .typeAlias, .unsafeAddressor, .unsafeMutableAddressor: fallthrough
case .variable, .willSet: return true
default: return false
}
}
var isAnyGeneric: Bool {
switch self {
case .structure, .class, .enum, .protocol, .protocolSymbolicReference, .otherNominalType, .typeAlias, .typeSymbolicReference: return true
default: return false
}
}
var isEntity: Bool {
return self == .type || isContext
}
var isRequirement: Bool {
switch self {
case .dependentGenericSameTypeRequirement, .dependentGenericLayoutRequirement: fallthrough
case .dependentGenericConformanceRequirement: return true
default: return false
}
}
var isFunctionAttr: Bool {
switch self {
case .functionSignatureSpecialization, .genericSpecialization, .inlinedGenericFunction: fallthrough
case .genericSpecializationNotReAbstracted, .genericPartialSpecialization: fallthrough
case .genericPartialSpecializationNotReAbstracted, .objCAttribute, .nonObjCAttribute: fallthrough
case .dynamicAttribute, .directMethodReferenceAttribute, .vTableAttribute, .partialApplyForwarder: fallthrough
case .partialApplyObjCForwarder, .outlinedVariable, .outlinedBridgedMethod, .mergedFunction: return true
default: return false
}
}
}
fileprivate extension Demangler {
func require<T>(_ optional: Optional<T>) throws -> T {
if let v = optional {
return v
} else {
throw failure
}
}
func require(_ value: Bool) throws {
if !value {
throw failure
}
}
var failure: Error {
return scanner.unexpectedError()
}
mutating func readManglingPrefix() throws {
switch (try scanner.readScalar(), try scanner.readScalar()) {
case ("_", "T"): try scanner.match(scalar: "0")
case ("_", "$") where scanner.conditional(scalar: "S"): return
case ("_", "$") where scanner.conditional(scalar: "s"): return
case ("$", "S"): return
case ("$", "s"): return
default: throw scanner.unexpectedError()
}
}
mutating func reset() {
nameStack = []
substitutions = []
words = []
scanner.reset()
}
mutating func popTopLevelInto(_ parent: inout SwiftSymbol) throws {
while var funcAttr = pop(where: { $0.isFunctionAttr }) {
switch funcAttr.kind {
case .partialApplyForwarder, .partialApplyObjCForwarder:
try popTopLevelInto(&funcAttr)
parent.children.append(funcAttr)
return
default:
parent.children.append(funcAttr)
}
}
for name in nameStack {
switch name.kind {
case .type: parent.children.append(try require(name.children.first))
default: parent.children.append(name)
}
}
try require(parent.children.count != 0)
}
mutating func demangleSymbol() throws -> SwiftSymbol {
reset()
if scanner.conditional(string: "_Tt") {
return try demangleObjCTypeName()
} else if scanner.conditional(string: "_T") {
isOldFunctionTypeMangling = true
try scanner.backtrack(count: 2)
}
try readManglingPrefix()
try parseAndPushNames()
var topLevel = SwiftSymbol(kind: .global)
try popTopLevelInto(&topLevel)
return topLevel
}
mutating func demangleType() throws -> SwiftSymbol {
reset()
try parseAndPushNames()
if let result = pop() {
return result
}
return SwiftSymbol(kind: .suffix, children: [], contents: .name(String(String.UnicodeScalarView(scanner.scalars))))
}
mutating func parseAndPushNames() throws {
while !scanner.isAtEnd {
nameStack.append(try demangleOperator())
}
}
mutating func demangleSymbolicReference() throws -> SwiftSymbol {
throw scanner.unexpectedError()
}
mutating func demangleOperator() throws -> SwiftSymbol {
switch try scanner.readScalar() {
case "\u{1}", "\u{2}", "\u{3}", "\u{4}", "\u{5}", "\u{6}", "\u{7}", "\u{8}", "\u{9}", "\u{A}", "\u{B}", "\u{C}":
try scanner.backtrack()
return try demangleSymbolicReference()
case "A": return try demangleMultiSubstitutions()
case "B": return try demangleBuiltinType()
case "C": return try demangleAnyGenericType(kind: .class)
case "D": return SwiftSymbol(kind: .typeMangling, child: try require(pop(kind: .type)))
case "E": return try demangleExtensionContext()
case "F": return try demanglePlainFunction()
case "G": return try demangleBoundGenericType()
case "H":
switch try scanner.readScalar() {
case "A": return try demangleDependentProtocolConformanceAssociated()
case "C": return try demangleConcreteProtocolConformance()
case "D": return try demangleDependentProtocolConformanceRoot()
case "I": return try demangleDependentProtocolConformanceInherited()
case "P": return SwiftSymbol(kind: .protocolConformanceRefInTypeModule, child: try popProtocol())
case "p": return SwiftSymbol(kind: .protocolConformanceRefInProtocolModule, child: try popProtocol())
default:
try scanner.backtrack(count: 2)
return try demangleIdentifier()
}
case "I": return try demangleImplFunctionType()
case "K": return SwiftSymbol(kind: .throwsAnnotation)
case "L": return try demangleLocalIdentifier()
case "M": return try demangleMetatype()
case "N": return SwiftSymbol(kind: .typeMetadata, child: try require(pop(kind: .type)))
case "O": return try demangleAnyGenericType(kind: .enum)
case "P": return try demangleAnyGenericType(kind: .protocol)
case "Q": return try demangleArchetype()
case "R": return try demangleGenericRequirement()
case "S": return try demangleStandardSubstitution()
case "T": return try demangleThunkOrSpecialization()
case "V": return try demangleAnyGenericType(kind: .structure)
case "W": return try demangleWitness()
case "X": return try demangleSpecialType()
case "Z": return SwiftSymbol(kind: .static, child: try require(pop(where: { $0.isEntity })))
case "a": return try demangleAnyGenericType(kind: .typeAlias)
case "c": return try require(popFunctionType(kind: .functionType))
case "d": return SwiftSymbol(kind: .variadicMarker)
case "f": return try demangleFunctionEntity()
case "g": return try demangleRetroactiveConformance()
case "h": return SwiftSymbol(typeWithChildKind: .shared, childChild: try require(popTypeAndGetChild()))
case "i": return try demangleSubscript()
case "l": return try demangleGenericSignature(hasParamCounts: false)
case "m": return SwiftSymbol(typeWithChildKind: .metatype, childChild: try require(pop(kind: .type)))
case "n": return SwiftSymbol(kind: .owned, child: try popTypeAndGetChild())
case "o": return try demangleOperatorIdentifier();
case "p": return try demangleProtocolListType();
case "q": return SwiftSymbol(kind: .type, child: try demangleGenericParamIndex())
case "r": return try demangleGenericSignature(hasParamCounts: true)
case "s": return SwiftSymbol(kind: .module, contents: .name(stdlibName))
case "t": return try popTuple()
case "u": return try demangleGenericType()
case "v": return try demangleVariable()
case "w": return try demangleValueWitness()
case "x": return SwiftSymbol(kind: .type, child: try getDependentGenericParamType(depth: 0, index: 0))
case "y": return SwiftSymbol(kind: .emptyList)
case "z": return SwiftSymbol(typeWithChildKind: .inOut, childChild: try require(popTypeAndGetChild()))
case "_": return SwiftSymbol(kind: .firstElementMarker)
case ".":
try scanner.backtrack()
return SwiftSymbol(kind: .suffix, contents: .name(scanner.remainder()))
default:
try scanner.backtrack()
return try demangleIdentifier()
}
}
mutating func demangleNatural() throws -> UInt64? {
return try scanner.conditionalInt()
}
mutating func demangleIndex() throws -> UInt64 {
if scanner.conditional(scalar: "_") {
return 0
}
let value = try require(demangleNatural())
try scanner.match(scalar: "_")
return value + 1
}
mutating func demangleIndexAsName() throws -> SwiftSymbol {
return SwiftSymbol(kind: .number, contents: .index(try demangleIndex()))
}
mutating func demangleMultiSubstitutions() throws -> SwiftSymbol {
var repeatCount: Int = -1
while true {
let c = try scanner.readScalar()
if c == "\0" {
throw scanner.unexpectedError()
} else if c.isLower {
let nd = try pushMultiSubstitutions(repeatCount: repeatCount, index: Int(c.value - UnicodeScalar("a").value))
nameStack.append(nd)
repeatCount = -1
continue
} else if c.isUpper {
return try pushMultiSubstitutions(repeatCount: repeatCount, index: Int(c.value - UnicodeScalar("A").value))
} else if c == "_" {
let idx = Int(repeatCount + 27)
return try require(substitutions.at(idx))
} else {
try scanner.backtrack()
repeatCount = Int(try demangleNatural() ?? 0)
}
}
}
mutating func pushMultiSubstitutions(repeatCount: Int, index: Int) throws -> SwiftSymbol {
try require(repeatCount <= maxRepeatCount)
let nd = try require(substitutions.at(index))
(0..<max(0, repeatCount - 1)).forEach { _ in nameStack.append(nd) }
return nd
}
mutating func pop() -> SwiftSymbol? {
return nameStack.popLast()
}
mutating func pop(kind: SwiftSymbol.Kind) -> SwiftSymbol? {
return nameStack.last?.kind == kind ? pop() : nil
}
mutating func pop(where cond: (SwiftSymbol.Kind) -> Bool) -> SwiftSymbol? {
return nameStack.last.map({ cond($0.kind) }) == true ? pop() : nil
}
mutating func popFunctionType(kind: SwiftSymbol.Kind) throws -> SwiftSymbol {
var name = SwiftSymbol(kind: kind)
if let ta = pop(kind: .throwsAnnotation) {
name.children.append(ta)
}
name.children.append(try popFunctionParams(kind: .argumentTuple))
name.children.append(try popFunctionParams(kind: .returnType))
return SwiftSymbol(kind: .type, child: name)
}
mutating func popFunctionParams(kind: SwiftSymbol.Kind) throws -> SwiftSymbol {
let paramsType: SwiftSymbol
if pop(kind: .emptyList) != nil {
return SwiftSymbol(kind: kind, child: SwiftSymbol(kind: .type, child: SwiftSymbol(kind: .tuple)))
} else {
paramsType = try require(pop(kind: .type))
}
if kind == .argumentTuple {
let params = try require(paramsType.children.first)
let numParams = params.kind == .tuple ? params.children.count : 1
return SwiftSymbol(kind: kind, children: [paramsType], contents: .index(UInt64(numParams)))
} else {
return SwiftSymbol(kind: kind, children: [paramsType])
}
}
mutating func getLabel(params: inout SwiftSymbol, idx: Int) throws -> SwiftSymbol {
if isOldFunctionTypeMangling {
let param = try require(params.children.at(idx))
if let label = param.children.enumerated().first(where: { $0.element.kind == .tupleElementName }) {
params.children[idx].children.remove(at: label.offset)
return SwiftSymbol(kind: .identifier, contents: .name(label.element.text ?? ""))
}
return SwiftSymbol(kind: .firstElementMarker)
}
return try require(pop())
}
mutating func popFunctionParamLabels(type: SwiftSymbol) throws -> SwiftSymbol? {
if !isOldFunctionTypeMangling && pop(kind: .emptyList) != nil {
return SwiftSymbol(kind: .labelList)
}
guard type.kind == .type else { return nil }
let topFuncType = try require(type.children.first)
let funcType: SwiftSymbol
if topFuncType.kind == .dependentGenericType {
funcType = try require(topFuncType.children.at(1)?.children.first)
} else {
funcType = topFuncType
}
guard funcType.kind == .functionType || funcType.kind == .noEscapeFunctionType else { return nil }
var parameterType = try require(funcType.children.first)
if parameterType.kind == .throwsAnnotation {
parameterType = try require(funcType.children.at(1))
}
try require(parameterType.kind == .argumentTuple)
guard let index = parameterType.index else { return nil }
let possibleTuple = parameterType.children.first?.children.first
guard !isOldFunctionTypeMangling, var tuple = possibleTuple, tuple.kind == .tuple else {
return SwiftSymbol(kind: .labelList)
}
var hasLabels = false
var children = [SwiftSymbol]()
for i in 0..<index {
let label = try getLabel(params: &tuple, idx: Int(i))
try require(label.kind == .identifier || label.kind == .firstElementMarker)
children.append(label)
hasLabels = hasLabels || (label.kind != .firstElementMarker)
}
if !hasLabels {
return SwiftSymbol(kind: .labelList)
}
return SwiftSymbol(kind: .labelList, children: isOldFunctionTypeMangling ? children : children.reversed())
}
mutating func popTuple() throws -> SwiftSymbol {
var children: [SwiftSymbol] = []
if pop(kind: .emptyList) == nil {
var firstElem = false
repeat {
firstElem = pop(kind: .firstElementMarker) != nil
var elemChildren: [SwiftSymbol] = pop(kind: .variadicMarker).map { [$0] } ?? []
if let ident = pop(kind: .identifier), case .name(let text) = ident.contents {
elemChildren.append(SwiftSymbol(kind: .tupleElementName, contents: .name(text)))
}
elemChildren.append(try require(pop(kind: .type)))
children.insert(SwiftSymbol(kind: .tupleElement, children: elemChildren), at: 0)
} while (!firstElem)
}
return SwiftSymbol(typeWithChildKind: .tuple, childChildren: children)
}
mutating func popTypeList() throws -> SwiftSymbol {
var children: [SwiftSymbol] = []
if pop(kind: .emptyList) == nil {
var firstElem = false
repeat {
firstElem = pop(kind: .firstElementMarker) != nil
children.insert(try require(pop(kind: .type)), at: 0)
} while (!firstElem)
}
return SwiftSymbol(kind: .typeList, children: children)
}
mutating func popProtocol() throws -> SwiftSymbol {
if let type = pop(kind: .type) {
try require(type.children.at(0)?.kind == .protocol)
return type
}