-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathSwiftifyImportMacro.swift
1517 lines (1395 loc) · 51 KB
/
SwiftifyImportMacro.swift
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
import SwiftDiagnostics
import SwiftParser
import SwiftSyntax
import SwiftSyntaxBuilder
import SwiftSyntaxMacros
// avoids depending on SwiftifyImport.swift
// all instances are reparsed and reinstantiated by the macro anyways,
// so linking is irrelevant
enum SwiftifyExpr: Hashable {
case param(_ index: Int)
case `return`
case `self`
}
extension SwiftifyExpr: CustomStringConvertible {
var description: String {
switch self {
case .param(let index): return ".param(\(index))"
case .return: return ".return"
case .self: return ".self"
}
}
}
enum DependenceType {
case borrow, copy
}
struct LifetimeDependence {
let dependsOn: SwiftifyExpr
let type: DependenceType
}
protocol ParamInfo: CustomStringConvertible {
var description: String { get }
var original: SyntaxProtocol { get }
var pointerIndex: SwiftifyExpr { get }
var nonescaping: Bool { get set }
var dependencies: [LifetimeDependence] { get set }
func getBoundsCheckedThunkBuilder(
_ base: BoundsCheckedThunkBuilder, _ funcDecl: FunctionDeclSyntax,
_ skipTrivialCount: Bool
) -> BoundsCheckedThunkBuilder
}
func tryGetParamName(_ funcDecl: FunctionDeclSyntax, _ expr: SwiftifyExpr) -> TokenSyntax? {
switch expr {
case .param(let i):
let funcParam = getParam(funcDecl, i - 1)
return funcParam.secondName ?? funcParam.firstName
case .`self`:
return .keyword(.self)
default: return nil
}
}
func getSwiftifyExprType(_ funcDecl: FunctionDeclSyntax, _ expr: SwiftifyExpr) -> TypeSyntax {
switch expr {
case .param(let i):
let funcParam = getParam(funcDecl, i - 1)
return funcParam.type
case .return:
return funcDecl.signature.returnClause!.type
case .self:
return TypeSyntax(IdentifierTypeSyntax(name: TokenSyntax("Self")))
}
}
struct CxxSpan: ParamInfo {
var pointerIndex: SwiftifyExpr
var nonescaping: Bool
var dependencies: [LifetimeDependence]
var typeMappings: [String: String]
var original: SyntaxProtocol
var description: String {
return "std::span(pointer: \(pointerIndex), nonescaping: \(nonescaping))"
}
func getBoundsCheckedThunkBuilder(
_ base: BoundsCheckedThunkBuilder, _ funcDecl: FunctionDeclSyntax,
_ skipTrivialCount: Bool
) -> BoundsCheckedThunkBuilder {
switch pointerIndex {
case .param(let i):
return CxxSpanThunkBuilder(
base: base, index: i - 1, signature: funcDecl.signature,
typeMappings: typeMappings, node: original, nonescaping: nonescaping)
case .return:
if dependencies.isEmpty {
return base
}
return CxxSpanReturnThunkBuilder(
base: base, signature: funcDecl.signature,
typeMappings: typeMappings, node: original)
case .self:
return base
}
}
}
struct CountedBy: ParamInfo {
var pointerIndex: SwiftifyExpr
var count: ExprSyntax
var sizedBy: Bool
var nonescaping: Bool
var dependencies: [LifetimeDependence]
var original: SyntaxProtocol
var description: String {
if sizedBy {
return ".sizedBy(pointer: \(pointerIndex), size: \"\(count)\", nonescaping: \(nonescaping))"
}
return ".countedBy(pointer: \(pointerIndex), count: \"\(count)\", nonescaping: \(nonescaping))"
}
func getBoundsCheckedThunkBuilder(
_ base: BoundsCheckedThunkBuilder, _ funcDecl: FunctionDeclSyntax,
_ skipTrivialCount: Bool
) -> BoundsCheckedThunkBuilder {
switch pointerIndex {
case .param(let i):
return CountedOrSizedPointerThunkBuilder(
base: base, index: i - 1, countExpr: count,
signature: funcDecl.signature,
nonescaping: nonescaping, isSizedBy: sizedBy, skipTrivialCount: skipTrivialCount)
case .return:
return CountedOrSizedReturnPointerThunkBuilder(
base: base, countExpr: count,
signature: funcDecl.signature,
nonescaping: nonescaping, isSizedBy: sizedBy, dependencies: dependencies)
case .self:
return base
}
}
}
struct RuntimeError: Error {
let description: String
init(_ description: String) {
self.description = description
}
var errorDescription: String? {
description
}
}
struct DiagnosticError: Error {
let description: String
let node: SyntaxProtocol
let notes: [Note]
init(_ description: String, node: SyntaxProtocol, notes: [Note] = []) {
self.description = description
self.node = node
self.notes = notes
}
var errorDescription: String? {
description
}
}
enum Mutability {
case Immutable
case Mutable
}
func getUnattributedType(_ type: TypeSyntax) -> TypeSyntax {
if let attributedType = type.as(AttributedTypeSyntax.self) {
return attributedType.baseType.trimmed
}
return type.trimmed
}
func getTypeName(_ type: TypeSyntax) throws -> TokenSyntax {
switch type.kind {
case .memberType:
let memberType = type.as(MemberTypeSyntax.self)!
if !memberType.baseType.isSwiftCoreModule {
throw DiagnosticError(
"expected pointer type in Swift core module, got type \(type) with base type \(memberType.baseType)",
node: type)
}
return memberType.name
case .identifierType:
return type.as(IdentifierTypeSyntax.self)!.name
case .attributedType:
return try getTypeName(type.as(AttributedTypeSyntax.self)!.baseType)
default:
throw DiagnosticError("expected pointer type, got \(type) with kind \(type.kind)", node: type)
}
}
func replaceTypeName(_ type: TypeSyntax, _ name: TokenSyntax) throws -> TypeSyntax {
if let memberType = type.as(MemberTypeSyntax.self) {
return TypeSyntax(memberType.with(\.name, name))
}
guard let idType = type.as(IdentifierTypeSyntax.self) else {
throw DiagnosticError("unexpected type \(type) with kind \(type.kind)", node: type)
}
return TypeSyntax(idType.with(\.name, name))
}
func replaceBaseType(_ type: TypeSyntax, _ base: TypeSyntax) -> TypeSyntax {
if let attributedType = type.as(AttributedTypeSyntax.self) {
return TypeSyntax(attributedType.with(\.baseType, base))
}
return base
}
// C++ type qualifiers, `const T` and `volatile T`, are encoded as fake generic
// types, `__cxxConst<T>` and `__cxxVolatile<T>` respectively. Remove those.
// Second return value is true if __cxxConst was stripped.
func dropQualifierGenerics(_ type: TypeSyntax) -> (TypeSyntax, Bool) {
guard let identifier = type.as(IdentifierTypeSyntax.self) else { return (type, false) }
guard let generic = identifier.genericArgumentClause else { return (type, false) }
guard let genericArg = generic.arguments.first else { return (type, false) }
guard case .type(let argType) = genericArg.argument else { return (type, false) }
switch identifier.name.text {
case "__cxxConst":
let (retType, _) = dropQualifierGenerics(argType)
return (retType, true)
case "__cxxVolatile":
return dropQualifierGenerics(argType)
default:
return (type, false)
}
}
// The generated type names for template instantiations sometimes contain
// encoded qualifiers for disambiguation purposes. We need to remove those.
func dropCxxQualifiers(_ type: TypeSyntax) -> (TypeSyntax, Bool) {
if let attributed = type.as(AttributedTypeSyntax.self) {
return dropCxxQualifiers(attributed.baseType)
}
return dropQualifierGenerics(type)
}
func getPointerMutability(text: String) -> Mutability? {
switch text {
case "UnsafePointer": return .Immutable
case "UnsafeMutablePointer": return .Mutable
case "UnsafeRawPointer": return .Immutable
case "UnsafeMutableRawPointer": return .Mutable
case "OpaquePointer": return .Immutable
default:
return nil
}
}
func isRawPointerType(text: String) -> Bool {
switch text {
case "UnsafeRawPointer": return true
case "UnsafeMutableRawPointer": return true
case "OpaquePointer": return true
default:
return false
}
}
// Remove std. or std.__1. prefix
func getUnqualifiedStdName(_ type: String) -> String? {
if type.hasPrefix("std.") {
var ty = type.dropFirst(4)
if ty.hasPrefix("__1.") {
ty = ty.dropFirst(4)
}
return String(ty)
}
return nil
}
func getSafePointerName(mut: Mutability, generateSpan: Bool, isRaw: Bool) -> TokenSyntax {
switch (mut, generateSpan, isRaw) {
case (.Immutable, true, true): return "RawSpan"
case (.Mutable, true, true): return "MutableRawSpan"
case (.Immutable, false, true): return "UnsafeRawBufferPointer"
case (.Mutable, false, true): return "UnsafeMutableRawBufferPointer"
case (.Immutable, true, false): return "Span"
case (.Mutable, true, false): return "MutableSpan"
case (.Immutable, false, false): return "UnsafeBufferPointer"
case (.Mutable, false, false): return "UnsafeMutableBufferPointer"
}
}
func hasOwnershipSpecifier(_ attrType: AttributedTypeSyntax) -> Bool {
return attrType.specifiers.contains(where: { e in
guard let simpleSpec = e.as(SimpleTypeSpecifierSyntax.self) else {
return false
}
let specifierText = simpleSpec.specifier.text
switch specifierText {
case "borrowing":
return true
case "inout":
return true
case "consuming":
return true
default:
return false
}
})
}
func transformType(
_ prev: TypeSyntax, _ generateSpan: Bool, _ isSizedBy: Bool, _ setMutableSpanInout: Bool
) throws -> TypeSyntax {
if let optType = prev.as(OptionalTypeSyntax.self) {
return TypeSyntax(
optType.with(
\.wrappedType,
try transformType(optType.wrappedType, generateSpan, isSizedBy, setMutableSpanInout)))
}
if let impOptType = prev.as(ImplicitlyUnwrappedOptionalTypeSyntax.self) {
return try transformType(impOptType.wrappedType, generateSpan, isSizedBy, setMutableSpanInout)
}
if let attrType = prev.as(AttributedTypeSyntax.self) {
// We insert 'inout' by default for MutableSpan, but it shouldn't override existing ownership
let setMutableSpanInoutNext = setMutableSpanInout && !hasOwnershipSpecifier(attrType)
return TypeSyntax(
attrType.with(
\.baseType,
try transformType(attrType.baseType, generateSpan, isSizedBy, setMutableSpanInoutNext)))
}
let name = try getTypeName(prev)
let text = name.text
let isRaw = isRawPointerType(text: text)
if isRaw && !isSizedBy {
throw DiagnosticError("raw pointers only supported for SizedBy", node: name)
}
if !isRaw && isSizedBy {
throw DiagnosticError("SizedBy only supported for raw pointers", node: name)
}
guard let kind: Mutability = getPointerMutability(text: text) else {
throw DiagnosticError(
"expected Unsafe[Mutable][Raw]Pointer type for type \(prev)"
+ " - first type token is '\(text)'", node: name)
}
let token = getSafePointerName(mut: kind, generateSpan: generateSpan, isRaw: isSizedBy)
let mainType =
if isSizedBy {
TypeSyntax(IdentifierTypeSyntax(name: token))
} else {
try replaceTypeName(prev, token)
}
if setMutableSpanInout && generateSpan && kind == .Mutable {
return TypeSyntax("inout \(mainType)")
}
return mainType
}
func isMutablePointerType(_ type: TypeSyntax) -> Bool {
if let optType = type.as(OptionalTypeSyntax.self) {
return isMutablePointerType(optType.wrappedType)
}
if let impOptType = type.as(ImplicitlyUnwrappedOptionalTypeSyntax.self) {
return isMutablePointerType(impOptType.wrappedType)
}
if let attrType = type.as(AttributedTypeSyntax.self) {
return isMutablePointerType(attrType.baseType)
}
do {
let name = try getTypeName(type)
let text = name.text
guard let kind: Mutability = getPointerMutability(text: text) else {
return false
}
return kind == .Mutable
} catch _ {
return false
}
}
protocol BoundsCheckedThunkBuilder {
func buildFunctionCall(_ pointerArgs: [Int: ExprSyntax]) throws -> ExprSyntax
func buildBoundsChecks() throws -> [CodeBlockItemSyntax.Item]
// The second component of the return value is true when only the return type of the
// function signature was changed.
func buildFunctionSignature(_ argTypes: [Int: TypeSyntax?], _ returnType: TypeSyntax?) throws
-> (FunctionSignatureSyntax, Bool)
}
func getParam(_ signature: FunctionSignatureSyntax, _ paramIndex: Int) -> FunctionParameterSyntax {
let params = signature.parameterClause.parameters
if paramIndex > 0 {
return params[params.index(params.startIndex, offsetBy: paramIndex)]
} else {
return params[params.startIndex]
}
}
func getParam(_ funcDecl: FunctionDeclSyntax, _ paramIndex: Int) -> FunctionParameterSyntax {
return getParam(funcDecl.signature, paramIndex)
}
struct FunctionCallBuilder: BoundsCheckedThunkBuilder {
let base: FunctionDeclSyntax
init(_ function: FunctionDeclSyntax) {
base = function
}
func buildBoundsChecks() throws -> [CodeBlockItemSyntax.Item] {
return []
}
func buildFunctionSignature(_ argTypes: [Int: TypeSyntax?], _ returnType: TypeSyntax?) throws
-> (FunctionSignatureSyntax, Bool)
{
var newParams = base.signature.parameterClause.parameters.enumerated().filter {
let type = argTypes[$0.offset]
// filter out deleted parameters, i.e. ones where argTypes[i] _contains_ nil
return type == nil || type! != nil
}.map { (i: Int, e: FunctionParameterSyntax) in
e.with(\.type, (argTypes[i] ?? e.type)!)
}
if let last = newParams.popLast() {
newParams.append(last.with(\.trailingComma, nil))
}
var sig = base.signature.with(
\.parameterClause.parameters, FunctionParameterListSyntax(newParams))
if returnType != nil {
sig = sig.with(\.returnClause!.type, returnType!)
}
return (sig, (argTypes.count == 0 && returnType != nil))
}
func buildFunctionCall(_ pointerArgs: [Int: ExprSyntax]) throws -> ExprSyntax {
let functionRef = DeclReferenceExprSyntax(baseName: base.name)
let args: [ExprSyntax] = base.signature.parameterClause.parameters.enumerated()
.map { (i: Int, param: FunctionParameterSyntax) in
let name = param.secondName ?? param.firstName
let declref = DeclReferenceExprSyntax(baseName: name)
return pointerArgs[i] ?? ExprSyntax(declref)
}
let labels: [TokenSyntax?] = base.signature.parameterClause.parameters.map { param in
let firstName = param.firstName.trimmed
if firstName.text == "_" {
return nil
}
return firstName
}
let labeledArgs: [LabeledExprSyntax] = zip(labels, args).enumerated().map { (i, e) in
let (label, arg) = e
var comma: TokenSyntax? = nil
if i < args.count - 1 {
comma = .commaToken()
}
let colon: TokenSyntax? = label != nil ? .colonToken() : nil
return LabeledExprSyntax(label: label, colon: colon, expression: arg, trailingComma: comma)
}
let call = ExprSyntax(
FunctionCallExprSyntax(
calledExpression: functionRef, leftParen: .leftParenToken(),
arguments: LabeledExprListSyntax(labeledArgs), rightParen: .rightParenToken()))
return "unsafe \(call)"
}
}
struct CxxSpanThunkBuilder: SpanBoundsThunkBuilder, ParamBoundsThunkBuilder {
public let base: BoundsCheckedThunkBuilder
public let index: Int
public let signature: FunctionSignatureSyntax
public let typeMappings: [String: String]
public let node: SyntaxProtocol
public let nonescaping: Bool
let isSizedBy: Bool = false
let isParameter: Bool = true
func buildBoundsChecks() throws -> [CodeBlockItemSyntax.Item] {
return try base.buildBoundsChecks()
}
func buildFunctionSignature(_ argTypes: [Int: TypeSyntax?], _ returnType: TypeSyntax?) throws
-> (FunctionSignatureSyntax, Bool)
{
var types = argTypes
types[index] = try newType
return try base.buildFunctionSignature(types, returnType)
}
func buildFunctionCall(_ pointerArgs: [Int: ExprSyntax]) throws -> ExprSyntax {
var args = pointerArgs
let typeName = getUnattributedType(oldType).description
assert(args[index] == nil)
let (_, isConst) = dropCxxQualifiers(try genericArg)
if isConst {
args[index] = ExprSyntax("\(raw: typeName)(\(raw: name))")
return try base.buildFunctionCall(args)
} else {
let unwrappedName = TokenSyntax("_\(name)Ptr")
args[index] = ExprSyntax("\(raw: typeName)(\(unwrappedName))")
let call = try base.buildFunctionCall(args)
// MutableSpan - unlike Span - cannot be bitcast to std::span due to being ~Copyable,
// so unwrap it to an UnsafeMutableBufferPointer that we can cast
let unwrappedCall = ExprSyntax(
"""
unsafe \(name).withUnsafeMutableBufferPointer { \(unwrappedName) in
return \(call)
}
""")
return unwrappedCall
}
}
}
struct CxxSpanReturnThunkBuilder: SpanBoundsThunkBuilder {
public let base: BoundsCheckedThunkBuilder
public let signature: FunctionSignatureSyntax
public let typeMappings: [String: String]
public let node: SyntaxProtocol
let isParameter: Bool = false
var oldType: TypeSyntax {
return signature.returnClause!.type
}
func buildBoundsChecks() throws -> [CodeBlockItemSyntax.Item] {
return try base.buildBoundsChecks()
}
func buildFunctionSignature(_ argTypes: [Int: TypeSyntax?], _ returnType: TypeSyntax?) throws
-> (FunctionSignatureSyntax, Bool)
{
assert(returnType == nil)
return try base.buildFunctionSignature(argTypes, newType)
}
func buildFunctionCall(_ pointerArgs: [Int: ExprSyntax]) throws -> ExprSyntax {
let call = try base.buildFunctionCall(pointerArgs)
let (_, isConst) = dropCxxQualifiers(try genericArg)
let cast =
if isConst {
"Span"
} else {
"MutableSpan"
}
return "unsafe _cxxOverrideLifetime(\(raw: cast)(_unsafeCxxSpan: \(call)), copying: ())"
}
}
protocol BoundsThunkBuilder: BoundsCheckedThunkBuilder {
var oldType: TypeSyntax { get }
var newType: TypeSyntax { get throws }
var signature: FunctionSignatureSyntax { get }
}
protocol SpanBoundsThunkBuilder: BoundsThunkBuilder {
var typeMappings: [String: String] { get }
var node: SyntaxProtocol { get }
var isParameter: Bool { get }
}
extension SpanBoundsThunkBuilder {
var desugaredType: TypeSyntax {
get throws {
let typeName = getUnattributedType(oldType).description
guard let desugaredTypeName = typeMappings[typeName] else {
throw DiagnosticError(
"unable to desugar type with name '\(typeName)'", node: node)
}
return TypeSyntax("\(raw: getUnqualifiedStdName(desugaredTypeName)!)")
}
}
var genericArg: TypeSyntax {
get throws {
guard let idType = try desugaredType.as(IdentifierTypeSyntax.self) else {
throw DiagnosticError(
"unexpected non-identifier type '\(try desugaredType)', expected a std::span type",
node: try desugaredType)
}
guard let genericArgumentClause = idType.genericArgumentClause else {
throw DiagnosticError(
"missing generic type argument clause expected after \(idType)", node: idType)
}
guard let firstArg = genericArgumentClause.arguments.first else {
throw DiagnosticError(
"expected at least 1 generic type argument for std::span type '\(idType)', found '\(genericArgumentClause)'",
node: genericArgumentClause.arguments)
}
guard let arg = TypeSyntax(firstArg.argument) else {
throw DiagnosticError(
"invalid generic type argument '\(firstArg.argument)'",
node: firstArg.argument)
}
return arg
}
}
var newType: TypeSyntax {
get throws {
let (strippedArg, isConst) = dropCxxQualifiers(try genericArg)
let mutablePrefix =
if isConst {
""
} else {
"Mutable"
}
let mainType = replaceBaseType(
oldType,
TypeSyntax("\(raw: mutablePrefix)Span<\(raw: strippedArg)>"))
if !isConst && isParameter {
return TypeSyntax("inout \(mainType)")
}
return mainType
}
}
}
protocol PointerBoundsThunkBuilder: BoundsThunkBuilder {
var nullable: Bool { get }
var isSizedBy: Bool { get }
var generateSpan: Bool { get }
var isParameter: Bool { get }
}
extension PointerBoundsThunkBuilder {
var nullable: Bool { return oldType.is(OptionalTypeSyntax.self) }
var newType: TypeSyntax {
get throws {
return try transformType(oldType, generateSpan, isSizedBy, isParameter)
}
}
}
protocol ParamBoundsThunkBuilder: BoundsThunkBuilder {
var index: Int { get }
var nonescaping: Bool { get }
}
extension ParamBoundsThunkBuilder {
var param: FunctionParameterSyntax {
return getParam(signature, index)
}
var oldType: TypeSyntax {
return param.type
}
var name: TokenSyntax {
return param.secondName ?? param.firstName
}
}
struct CountedOrSizedReturnPointerThunkBuilder: PointerBoundsThunkBuilder {
public let base: BoundsCheckedThunkBuilder
public let countExpr: ExprSyntax
public let signature: FunctionSignatureSyntax
public let nonescaping: Bool
public let isSizedBy: Bool
public let dependencies: [LifetimeDependence]
let isParameter: Bool = false
var generateSpan: Bool { !dependencies.isEmpty }
var oldType: TypeSyntax {
return signature.returnClause!.type
}
func buildFunctionSignature(_ argTypes: [Int: TypeSyntax?], _ returnType: TypeSyntax?) throws
-> (FunctionSignatureSyntax, Bool)
{
assert(returnType == nil)
return try base.buildFunctionSignature(argTypes, newType)
}
func buildBoundsChecks() throws -> [CodeBlockItemSyntax.Item] {
return try base.buildBoundsChecks()
}
func buildFunctionCall(_ pointerArgs: [Int: ExprSyntax]) throws -> ExprSyntax {
let call = try base.buildFunctionCall(pointerArgs)
let startLabel =
if generateSpan {
"_unsafeStart"
} else {
"start"
}
var cast = try newType
if nullable {
if let optType = cast.as(OptionalTypeSyntax.self) {
cast = optType.wrappedType
}
return """
{ () in
let _resultValue = \(call)
if unsafe _resultValue == nil {
return nil
} else {
return unsafe \(raw: cast)(\(raw: startLabel): _resultValue!, count: Int(\(countExpr)))
}
}()
"""
}
return
"""
unsafe \(raw: cast)(\(raw: startLabel): \(call), count: Int(\(countExpr)))
"""
}
}
struct CountedOrSizedPointerThunkBuilder: ParamBoundsThunkBuilder, PointerBoundsThunkBuilder {
public let base: BoundsCheckedThunkBuilder
public let index: Int
public let countExpr: ExprSyntax
public let signature: FunctionSignatureSyntax
public let nonescaping: Bool
public let isSizedBy: Bool
public let skipTrivialCount: Bool
let isParameter: Bool = true
var generateSpan: Bool { nonescaping }
func buildFunctionSignature(_ argTypes: [Int: TypeSyntax?], _ returnType: TypeSyntax?) throws
-> (FunctionSignatureSyntax, Bool)
{
var types = argTypes
types[index] = try newType
if skipTrivialCount {
if let countVar = countExpr.as(DeclReferenceExprSyntax.self) {
let i = try getParameterIndexForDeclRef(signature.parameterClause.parameters, countVar)
types[i] = nil as TypeSyntax?
}
}
return try base.buildFunctionSignature(types, returnType)
}
func buildBoundsChecks() throws -> [CodeBlockItemSyntax.Item] {
var res = try base.buildBoundsChecks()
let countName: TokenSyntax = "_\(raw: name)Count"
let count: VariableDeclSyntax = try VariableDeclSyntax(
"let \(countName): some BinaryInteger = \(countExpr)")
res.append(CodeBlockItemSyntax.Item(count))
let countCheck = ExprSyntax(
"""
if \(getCount()) < \(countName) || \(countName) < 0 {
fatalError("bounds check failure when calling unsafe function")
}
""")
res.append(CodeBlockItemSyntax.Item(countCheck))
return res
}
func unwrapIfNullable(_ expr: ExprSyntax) -> ExprSyntax {
if nullable {
return ExprSyntax(ForceUnwrapExprSyntax(expression: expr))
}
return expr
}
func unwrapIfNonnullable(_ expr: ExprSyntax) -> ExprSyntax {
if !nullable {
return ExprSyntax(ForceUnwrapExprSyntax(expression: expr))
}
return expr
}
func castIntToTargetType(expr: ExprSyntax, type: TypeSyntax) -> ExprSyntax {
if type.canRepresentBasicType(type: Int.self) {
return expr
}
return ExprSyntax("\(type)(exactly: \(expr))!")
}
func buildUnwrapCall(_ argOverrides: [Int: ExprSyntax]) throws -> ExprSyntax {
let unwrappedName = TokenSyntax("_\(name)Ptr")
var args = argOverrides
let argExpr = ExprSyntax("\(unwrappedName).baseAddress")
assert(args[index] == nil)
args[index] = try castPointerToOpaquePointer(unwrapIfNonnullable(argExpr))
let call = try base.buildFunctionCall(args)
let ptrRef = unwrapIfNullable(ExprSyntax(DeclReferenceExprSyntax(baseName: name)))
let funcName =
switch (isSizedBy, isMutablePointerType(oldType)) {
case (true, true): "withUnsafeMutableBytes"
case (true, false): "withUnsafeBytes"
case (false, true): "withUnsafeMutableBufferPointer"
case (false, false): "withUnsafeBufferPointer"
}
let unwrappedCall = ExprSyntax(
"""
unsafe \(ptrRef).\(raw: funcName) { \(unwrappedName) in
return \(call)
}
""")
return unwrappedCall
}
func getCount() -> ExprSyntax {
let countName = isSizedBy && generateSpan ? "byteCount" : "count"
if nullable {
return ExprSyntax("\(name)?.\(raw: countName) ?? 0")
}
return ExprSyntax("\(name).\(raw: countName)")
}
func peelOptionalType(_ type: TypeSyntax) -> TypeSyntax {
if let optType = type.as(OptionalTypeSyntax.self) {
return optType.wrappedType
}
if let impOptType = type.as(ImplicitlyUnwrappedOptionalTypeSyntax.self) {
return impOptType.wrappedType
}
return type
}
func castPointerToOpaquePointer(_ baseAddress: ExprSyntax) throws -> ExprSyntax {
let i = try getParameterIndexForParamName(signature.parameterClause.parameters, name)
let type = peelOptionalType(getParam(signature, i).type)
if type.canRepresentBasicType(type: OpaquePointer.self) {
return ExprSyntax("OpaquePointer(\(baseAddress))")
}
return baseAddress
}
func getPointerArg() throws -> ExprSyntax {
if nullable {
return ExprSyntax("\(name)?.baseAddress")
}
return ExprSyntax("\(name).baseAddress!")
}
func buildFunctionCall(_ argOverrides: [Int: ExprSyntax]) throws -> ExprSyntax {
var args = argOverrides
if skipTrivialCount {
assert(
countExpr.is(DeclReferenceExprSyntax.self) || countExpr.is(IntegerLiteralExprSyntax.self))
if let countVar = countExpr.as(DeclReferenceExprSyntax.self) {
let i = try getParameterIndexForDeclRef(signature.parameterClause.parameters, countVar)
assert(args[i] == nil)
args[i] = castIntToTargetType(expr: getCount(), type: getParam(signature, i).type)
}
}
assert(args[index] == nil)
if generateSpan {
assert(nonescaping)
let unwrappedCall = try buildUnwrapCall(args)
if nullable {
var nullArgs = args
nullArgs[index] = ExprSyntax(NilLiteralExprSyntax(nilKeyword: .keyword(.nil)))
return ExprSyntax(
"""
{ () in return if \(name) == nil {
\(try base.buildFunctionCall(nullArgs))
} else {
\(unwrappedCall)
} }()
""")
}
return unwrappedCall
}
args[index] = try castPointerToOpaquePointer(getPointerArg())
return try base.buildFunctionCall(args)
}
}
func getArgumentByName(_ argumentList: LabeledExprListSyntax, _ name: String) throws -> ExprSyntax {
guard
let arg = argumentList.first(where: {
return $0.label?.text == name
})
else {
throw DiagnosticError(
"no argument with name '\(name)' in '\(argumentList)'", node: argumentList)
}
return arg.expression
}
func getOptionalArgumentByName(_ argumentList: LabeledExprListSyntax, _ name: String) -> ExprSyntax?
{
return argumentList.first(where: {
$0.label?.text == name
})?.expression
}
func getParameterIndexForParamName(
_ parameterList: FunctionParameterListSyntax, _ tok: TokenSyntax
) throws -> Int {
let name = tok.text
guard
let index = parameterList.enumerated().first(where: {
(_: Int, param: FunctionParameterSyntax) in
let paramenterName = param.secondName ?? param.firstName
return paramenterName.trimmed.text == name
})?.offset
else {
throw DiagnosticError("no parameter with name '\(name)' in '\(parameterList)'", node: tok)
}
return index
}
func getParameterIndexForDeclRef(
_ parameterList: FunctionParameterListSyntax, _ ref: DeclReferenceExprSyntax
) throws -> Int {
return try getParameterIndexForParamName((parameterList), ref.baseName)
}
func parseEnumName(_ expr: ExprSyntax) throws -> String {
var exprLocal = expr
if let callExpr = expr.as(FunctionCallExprSyntax.self) {
exprLocal = callExpr.calledExpression
}
guard let dotExpr = exprLocal.as(MemberAccessExprSyntax.self) else {
throw DiagnosticError(
"expected enum literal as argument, got '\(expr)'",
node: expr)
}
return dotExpr.declName.baseName.text
}
func parseEnumArgs(_ expr: ExprSyntax) throws -> LabeledExprListSyntax {
guard let callExpr = expr.as(FunctionCallExprSyntax.self) else {
throw DiagnosticError(
"expected call to enum constructor, got '\(expr)'",
node: expr)
}
return callExpr.arguments
}
func getIntLiteralValue(_ expr: ExprSyntax) throws -> Int {
guard let intLiteral = expr.as(IntegerLiteralExprSyntax.self) else {
throw DiagnosticError("expected integer literal, got '\(expr)'", node: expr)
}
guard let res = intLiteral.representedLiteralValue else {
throw DiagnosticError("expected integer literal, got '\(expr)'", node: expr)
}
return res
}
func getBoolLiteralValue(_ expr: ExprSyntax) throws -> Bool {
guard let boolLiteral = expr.as(BooleanLiteralExprSyntax.self) else {
throw DiagnosticError("expected boolean literal, got '\(expr)'", node: expr)
}
switch boolLiteral.literal.tokenKind {
case .keyword(.true):
return true
case .keyword(.false):
return false
default:
throw DiagnosticError("expected bool literal, got '\(expr)'", node: expr)
}
}
func parseSwiftifyExpr(_ expr: ExprSyntax) throws -> SwiftifyExpr {
let enumName = try parseEnumName(expr)
switch enumName {
case "param":
let argumentList = try parseEnumArgs(expr)
if argumentList.count != 1 {
throw DiagnosticError(
"expected single argument to _SwiftifyExpr.param, got \(argumentList.count) arguments",
node: expr)
}
let pointerParamIndexArg = argumentList[argumentList.startIndex]
let pointerParamIndex: Int = try getIntLiteralValue(pointerParamIndexArg.expression)
return .param(pointerParamIndex)
case "return": return .return
case "self": return .`self`
default:
throw DiagnosticError(
"expected 'param', 'return', or 'self', got '\(enumName)'",
node: expr)
}
}
func parseCountedByEnum(
_ enumConstructorExpr: FunctionCallExprSyntax, _ signature: FunctionSignatureSyntax
) throws -> ParamInfo {
let argumentList = enumConstructorExpr.arguments
let pointerExprArg = try getArgumentByName(argumentList, "pointer")
let pointerExpr: SwiftifyExpr = try parseSwiftifyExpr(pointerExprArg)
let countExprArg = try getArgumentByName(argumentList, "count")
guard let countExprStringLit = countExprArg.as(StringLiteralExprSyntax.self) else {
throw DiagnosticError(
"expected string literal for 'count' parameter, got \(countExprArg)", node: countExprArg)
}
let unwrappedCountExpr = ExprSyntax(stringLiteral: countExprStringLit.representedLiteralValue!)
if let countVar = unwrappedCountExpr.as(DeclReferenceExprSyntax.self) {
// Perform this lookup here so we can override the position to point to the string literal
// instead of line 1, column 1
do {
_ = try getParameterIndexForDeclRef(signature.parameterClause.parameters, countVar)
} catch let error as DiagnosticError {
throw DiagnosticError(error.description, node: countExprStringLit, notes: error.notes)
}
}
return CountedBy(
pointerIndex: pointerExpr, count: unwrappedCountExpr, sizedBy: false,