forked from swiftlang/swift-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwiftFunctionSignature.swift
More file actions
482 lines (428 loc) · 15.4 KB
/
SwiftFunctionSignature.swift
File metadata and controls
482 lines (428 loc) · 15.4 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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift.org project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift.org project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import SwiftSyntax
import SwiftSyntaxBuilder
enum SwiftGenericRequirement: Equatable {
case inherits(SwiftType, SwiftType)
case equals(SwiftType, SwiftType)
}
/// Provides a complete signature for a Swift function, which includes its
/// parameters and return type.
public struct SwiftFunctionSignature: Equatable {
var selfParameter: SwiftSelfParameter?
var parameters: [SwiftParameter]
var result: SwiftResult
var effectSpecifiers: [SwiftEffectSpecifier]
var genericParameters: [SwiftGenericParameterDeclaration]
var genericRequirements: [SwiftGenericRequirement]
var isAsync: Bool {
effectSpecifiers.contains(.async)
}
var isThrowing: Bool {
effectSpecifiers.contains(.throws)
}
init(
selfParameter: SwiftSelfParameter? = nil,
parameters: [SwiftParameter],
result: SwiftResult,
effectSpecifiers: [SwiftEffectSpecifier],
genericParameters: [SwiftGenericParameterDeclaration],
genericRequirements: [SwiftGenericRequirement]
) {
self.selfParameter = selfParameter
self.parameters = parameters
self.result = result
self.effectSpecifiers = effectSpecifiers
self.genericParameters = genericParameters
self.genericRequirements = genericRequirements
}
}
/// Describes the "self" parameter of a Swift function signature.
enum SwiftSelfParameter: Equatable {
/// 'self' is an instance parameter.
case instance(convention: SwiftParameterConvention, swiftType: SwiftType)
/// 'self' is a metatype for a static method. We only need the type to
/// form the call.
case staticMethod(SwiftType)
/// 'self' is the type for a call to an initializer. We only need the type
/// to form the call.
case initializer(SwiftType)
var selfType: SwiftType {
switch self {
case .instance(_, let swiftType), .staticMethod(let swiftType), .initializer(let swiftType):
return swiftType
}
}
}
extension SwiftFunctionSignature {
init(
_ node: InitializerDeclSyntax,
enclosingType: SwiftType?,
lookupContext: SwiftTypeLookupContext
) throws {
guard let enclosingType else {
throw SwiftFunctionTranslationError.missingEnclosingType(node)
}
let (genericParams, genericRequirements) = try Self.translateGenericParameters(
parameterClause: node.genericParameterClause,
whereClause: node.genericWhereClause,
lookupContext: lookupContext
)
let (parameters, effectSpecifiers) = try Self.translateFunctionSignature(
node.signature,
lookupContext: lookupContext
)
let type = node.optionalMark != nil ? .optional(enclosingType) : enclosingType
self.init(
selfParameter: .initializer(enclosingType),
parameters: parameters,
result: SwiftResult(convention: .direct, type: type),
effectSpecifiers: effectSpecifiers,
genericParameters: genericParams,
genericRequirements: genericRequirements
)
}
init(
_ node: EnumCaseElementSyntax,
enclosingType: SwiftType,
lookupContext: SwiftTypeLookupContext
) throws {
let parameters = try node.parameterClause?.parameters.map { param in
try SwiftParameter(param, lookupContext: lookupContext)
}
self.init(
selfParameter: .initializer(enclosingType),
parameters: parameters ?? [],
result: SwiftResult(convention: .direct, type: enclosingType),
effectSpecifiers: [],
genericParameters: [],
genericRequirements: []
)
}
init(
_ node: FunctionDeclSyntax,
enclosingType: SwiftType?,
lookupContext: SwiftTypeLookupContext
) throws {
let (genericParams, genericRequirements) = try Self.translateGenericParameters(
parameterClause: node.genericParameterClause,
whereClause: node.genericWhereClause,
lookupContext: lookupContext
)
// If this is a member of a type, so we will have a self parameter. Figure out the
// type and convention for the self parameter.
let selfParameter: SwiftSelfParameter?
if let enclosingType {
var isMutating = false
var isConsuming = false
var isStatic = false
for modifier in node.modifiers {
switch modifier.name.tokenKind {
case .keyword(.mutating): isMutating = true
case .keyword(.static): isStatic = true
case .keyword(.consuming): isConsuming = true
case .keyword(.class): throw SwiftFunctionTranslationError.classMethod(modifier.name)
default: break
}
}
if isStatic {
selfParameter = .staticMethod(enclosingType)
} else {
selfParameter = .instance(
convention: isMutating ? .inout : isConsuming ? .consuming : .byValue,
swiftType: enclosingType
)
}
} else {
selfParameter = nil
}
// Translate the parameters.
let (parameters, effectSpecifiers) = try Self.translateFunctionSignature(
node.signature,
lookupContext: lookupContext
)
// Translate the result type.
let result: SwiftResult
if let resultType = node.signature.returnClause?.type {
result = try SwiftResult(
convention: .direct,
type: SwiftType(resultType, lookupContext: lookupContext)
)
} else {
result = .void
}
self.init(
selfParameter: selfParameter,
parameters: parameters,
result: result,
effectSpecifiers: effectSpecifiers,
genericParameters: genericParams,
genericRequirements: genericRequirements
)
}
static func translateGenericParameters(
parameterClause: GenericParameterClauseSyntax?,
whereClause: GenericWhereClauseSyntax?,
lookupContext: SwiftTypeLookupContext
) throws -> (parameters: [SwiftGenericParameterDeclaration], requirements: [SwiftGenericRequirement]) {
var params: [SwiftGenericParameterDeclaration] = []
var requirements: [SwiftGenericRequirement] = []
// Parameter clause
if let parameterClause {
for parameterNode in parameterClause.parameters {
guard parameterNode.specifier == nil else {
throw SwiftFunctionTranslationError.genericParameterSpecifier(parameterNode)
}
let param =
try lookupContext.typeDeclaration(for: parameterNode, sourceFilePath: "FIXME_HAS_NO_PATH.swift")
as! SwiftGenericParameterDeclaration
params.append(param)
if let inheritedNode = parameterNode.inheritedType {
let inherited = try SwiftType(inheritedNode, lookupContext: lookupContext)
requirements.append(.inherits(.genericParameter(param), inherited))
}
}
}
// Where clause
if let whereClause {
for requirementNode in whereClause.requirements {
let requirement: SwiftGenericRequirement
switch requirementNode.requirement {
case .conformanceRequirement(let conformance):
requirement = .inherits(
try SwiftType(conformance.leftType, lookupContext: lookupContext),
try SwiftType(conformance.rightType, lookupContext: lookupContext)
)
case .sameTypeRequirement(let sameType):
guard let leftType = sameType.leftType.as(TypeSyntax.self) else {
throw SwiftFunctionTranslationError.expressionInGenericRequirement(requirementNode)
}
guard let rightType = sameType.rightType.as(TypeSyntax.self) else {
throw SwiftFunctionTranslationError.expressionInGenericRequirement(requirementNode)
}
requirement = .equals(
try SwiftType(leftType, lookupContext: lookupContext),
try SwiftType(rightType, lookupContext: lookupContext)
)
case .layoutRequirement:
throw SwiftFunctionTranslationError.layoutRequirement(requirementNode)
}
requirements.append(requirement)
}
}
return (params, requirements)
}
/// Translate the function signature, returning the list of translated
/// parameters and effect specifiers.
static func translateFunctionSignature(
_ signature: FunctionSignatureSyntax,
lookupContext: SwiftTypeLookupContext
) throws -> ([SwiftParameter], [SwiftEffectSpecifier]) {
var effectSpecifiers = [SwiftEffectSpecifier]()
if signature.effectSpecifiers?.throwsClause != nil {
effectSpecifiers.append(.throws)
}
if signature.effectSpecifiers?.asyncSpecifier != nil {
effectSpecifiers.append(.async)
}
let parameters = try signature.parameterClause.parameters.map { param in
try SwiftParameter(param, lookupContext: lookupContext)
}
return (parameters, effectSpecifiers)
}
init(
_ varNode: VariableDeclSyntax,
isSet: Bool,
enclosingType: SwiftType?,
lookupContext: SwiftTypeLookupContext
) throws {
self.selfParameter = try Self.variableSelfParameter(
for: DeclSyntax(varNode),
enclosingType: enclosingType,
isSet: isSet
)
guard let binding = varNode.bindings.first, varNode.bindings.count == 1 else {
throw SwiftFunctionTranslationError.multipleBindings(varNode)
}
guard let varTypeNode = binding.typeAnnotation?.type else {
throw SwiftFunctionTranslationError.missingTypeAnnotation(varNode)
}
let valueType = try SwiftType(varTypeNode, lookupContext: lookupContext)
var effectSpecifiers: [SwiftEffectSpecifier]? = nil
switch binding.accessorBlock?.accessors {
case .getter(let getter):
if let getter = getter.as(AccessorDeclSyntax.self) {
effectSpecifiers = try Self.effectSpecifiers(from: getter)
}
case .accessors(let accessors):
if let getter = accessors.first(where: { $0.accessorSpecifier.tokenKind == .keyword(.get) }) {
effectSpecifiers = try Self.effectSpecifiers(from: getter)
}
default:
break
}
self.effectSpecifiers = effectSpecifiers ?? []
if isSet {
self.parameters = [
SwiftParameter(convention: .byValue, parameterName: "newValue", type: valueType)
]
self.result = .void
} else {
self.parameters = []
self.result = .init(convention: .direct, type: valueType)
}
self.genericParameters = []
self.genericRequirements = []
}
init(
_ subscriptNode: SubscriptDeclSyntax,
isSet: Bool,
enclosingType: SwiftType?,
lookupContext: SwiftTypeLookupContext
) throws {
self.selfParameter = try Self.variableSelfParameter(
for: DeclSyntax(subscriptNode),
enclosingType: enclosingType,
isSet: isSet
)
let valueType: SwiftType = try SwiftType(subscriptNode.returnClause.type, lookupContext: lookupContext)
var nodeParameters = try subscriptNode.parameterClause.parameters.map { param in
try SwiftParameter(param, lookupContext: lookupContext)
}
var effectSpecifiers: [SwiftEffectSpecifier]? = nil
switch subscriptNode.accessorBlock?.accessors {
case .getter(let getter):
if let getter = getter.as(AccessorDeclSyntax.self) {
effectSpecifiers = try Self.effectSpecifiers(from: getter)
}
case .accessors(let accessors):
if let getter = accessors.first(where: { $0.accessorSpecifier.tokenKind == .keyword(.get) }) {
effectSpecifiers = try Self.effectSpecifiers(from: getter)
}
default:
break
}
self.effectSpecifiers = effectSpecifiers ?? []
if isSet {
nodeParameters.append(SwiftParameter(convention: .byValue, parameterName: "newValue", type: valueType))
self.result = .void
} else {
self.result = .init(convention: .direct, type: valueType)
}
self.parameters = nodeParameters
self.genericParameters = []
self.genericRequirements = []
}
private static func effectSpecifiers(from decl: AccessorDeclSyntax) throws -> [SwiftEffectSpecifier] {
var effectSpecifiers = [SwiftEffectSpecifier]()
if decl.effectSpecifiers?.throwsClause != nil {
effectSpecifiers.append(.throws)
}
if decl.effectSpecifiers?.asyncSpecifier != nil {
effectSpecifiers.append(.async)
}
return effectSpecifiers
}
private static func variableSelfParameter(
for decl: DeclSyntax,
enclosingType: SwiftType?,
isSet: Bool
) throws -> SwiftSelfParameter? {
let modifiers: DeclModifierListSyntax? =
switch decl.as(DeclSyntaxEnum.self) {
case .variableDecl(let varDecl): varDecl.modifiers
case .subscriptDecl(let subscriptDecl): subscriptDecl.modifiers
default: nil
}
guard let modifiers else {
return nil
}
// If this is a member of a type, so we will have a self parameter. Figure out the
// type and convention for the self parameter.
if let enclosingType {
var isStatic = false
for modifier in modifiers {
switch modifier.name.tokenKind {
case .keyword(.static): isStatic = true
case .keyword(.class): throw SwiftFunctionTranslationError.classMethod(modifier.name)
default: break
}
}
if isStatic {
return .staticMethod(enclosingType)
} else {
return .instance(
convention: isSet && !enclosingType.isReferenceType ? .inout : .byValue,
swiftType: enclosingType
)
}
} else {
return nil
}
}
}
extension VariableDeclSyntax {
/// Determine what operations (i.e. get and/or set) supported in this `VariableDeclSyntax`
///
/// - Parameters:
/// - binding the pattern binding in this declaration.
func supportedAccessorKinds(binding: PatternBindingSyntax) -> AccessorBlockSyntax.SupportedAccessorKinds {
if self.bindingSpecifier.tokenKind == .keyword(.let) {
return [.get]
}
if let accessorBlock = binding.accessorBlock {
return accessorBlock.supportedAccessorKinds()
}
return [.get, .set]
}
}
extension AccessorBlockSyntax {
struct SupportedAccessorKinds: OptionSet {
var rawValue: UInt8
static var get: Self = .init(rawValue: 1 << 0)
static var set: Self = .init(rawValue: 1 << 1)
}
/// Determine what operations (i.e. get and/or set) supported in this `AccessorBlockSyntax`
func supportedAccessorKinds() -> SupportedAccessorKinds {
switch self.accessors {
case .getter:
return [.get]
case .accessors(let accessors):
for accessor in accessors {
switch accessor.accessorSpecifier.tokenKind {
// Existence of any write accessor or observer implies this supports read/write.
case .keyword(.set), .keyword(._modify), .keyword(.unsafeMutableAddress),
.keyword(.willSet), .keyword(.didSet):
return [.get, .set]
default: // Ignore willSet/didSet and unknown accessors.
break
}
}
return [.get]
}
}
}
enum SwiftFunctionTranslationError: Error {
case `throws`(ThrowsClauseSyntax)
case async(TokenSyntax)
case classMethod(TokenSyntax)
case missingEnclosingType(InitializerDeclSyntax)
case failableInitializer(InitializerDeclSyntax)
case multipleBindings(VariableDeclSyntax)
case missingTypeAnnotation(VariableDeclSyntax)
case unsupportedAccessor(AccessorDeclSyntax)
case genericParameterSpecifier(GenericParameterSyntax)
case expressionInGenericRequirement(GenericRequirementSyntax)
case layoutRequirement(GenericRequirementSyntax)
}