|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +import SwiftSyntax |
| 14 | +import SwiftSyntaxMacros |
| 15 | + |
| 16 | +extension SyntaxCollection { |
| 17 | + mutating func removeLast() { |
| 18 | + self.remove(at: self.index(before: self.endIndex)) |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +public struct AddAsyncMacro: PeerMacro { |
| 23 | + public static func expansion< |
| 24 | + Context: MacroExpansionContext, |
| 25 | + Declaration: DeclSyntaxProtocol |
| 26 | + >( |
| 27 | + of node: AttributeSyntax, |
| 28 | + providingPeersOf declaration: Declaration, |
| 29 | + in context: Context |
| 30 | + ) throws -> [DeclSyntax] { |
| 31 | + |
| 32 | + // Only on functions at the moment. |
| 33 | + guard let funcDecl = declaration.as(FunctionDeclSyntax.self) else { |
| 34 | + throw CustomError.message("@addAsync only works on functions") |
| 35 | + } |
| 36 | + |
| 37 | + // This only makes sense for non async functions. |
| 38 | + if funcDecl.signature.effectSpecifiers?.asyncSpecifier != nil { |
| 39 | + throw CustomError.message( |
| 40 | + "@addAsync requires an non async function" |
| 41 | + ) |
| 42 | + } |
| 43 | + |
| 44 | + // This only makes sense void functions |
| 45 | + if funcDecl.signature.returnClause?.type.with(\.leadingTrivia, []).with(\.trailingTrivia, []).description != "Void" { |
| 46 | + throw CustomError.message( |
| 47 | + "@addAsync requires an function that returns void" |
| 48 | + ) |
| 49 | + } |
| 50 | + |
| 51 | + // Requires a completion handler block as last parameter |
| 52 | + guard let completionHandlerParameterAttribute = funcDecl.signature.parameterClause.parameters.last?.type.as(AttributedTypeSyntax.self), |
| 53 | + let completionHandlerParameter = completionHandlerParameterAttribute.baseType.as(FunctionTypeSyntax.self) |
| 54 | + else { |
| 55 | + throw CustomError.message( |
| 56 | + "@addAsync requires an function that has a completion handler as last parameter" |
| 57 | + ) |
| 58 | + } |
| 59 | + |
| 60 | + // Completion handler needs to return Void |
| 61 | + if completionHandlerParameter.returnClause.type.with(\.leadingTrivia, []).with(\.trailingTrivia, []).description != "Void" { |
| 62 | + throw CustomError.message( |
| 63 | + "@addAsync requires an function that has a completion handler that returns Void" |
| 64 | + ) |
| 65 | + } |
| 66 | + |
| 67 | + let returnType = completionHandlerParameter.parameters.first?.type |
| 68 | + |
| 69 | + let isResultReturn = returnType?.children(viewMode: .all).first?.description == "Result" |
| 70 | + let successReturnType = isResultReturn ? returnType!.as(IdentifierTypeSyntax.self)!.genericArgumentClause?.arguments.first!.argument : returnType |
| 71 | + |
| 72 | + // Remove completionHandler and comma from the previous parameter |
| 73 | + var newParameterList = funcDecl.signature.parameterClause.parameters |
| 74 | + newParameterList.removeLast() |
| 75 | + let newParameterListLastParameter = newParameterList.last! |
| 76 | + newParameterList.removeLast() |
| 77 | + newParameterList.append(newParameterListLastParameter.with(\.trailingTrivia, []).with(\.trailingComma, nil)) |
| 78 | + |
| 79 | + // Drop the @addAsync attribute from the new declaration. |
| 80 | + let newAttributeList = funcDecl.attributes.filter { |
| 81 | + guard case let .attribute(attribute) = $0, |
| 82 | + let attributeType = attribute.attributeName.as(IdentifierTypeSyntax.self), |
| 83 | + let nodeType = node.attributeName.as(IdentifierTypeSyntax.self) |
| 84 | + else { |
| 85 | + return true |
| 86 | + } |
| 87 | + |
| 88 | + return attributeType.name.text != nodeType.name.text |
| 89 | + } |
| 90 | + |
| 91 | + let callArguments: [String] = newParameterList.map { param in |
| 92 | + let argName = param.secondName ?? param.firstName |
| 93 | + |
| 94 | + let paramName = param.firstName |
| 95 | + if paramName.text != "_" { |
| 96 | + return "\(paramName.text): \(argName.text)" |
| 97 | + } |
| 98 | + |
| 99 | + return "\(argName.text)" |
| 100 | + } |
| 101 | + |
| 102 | + let switchBody: ExprSyntax = |
| 103 | + """ |
| 104 | + switch returnValue { |
| 105 | + case .success(let value): |
| 106 | + continuation.resume(returning: value) |
| 107 | + case .failure(let error): |
| 108 | + continuation.resume(throwing: error) |
| 109 | + } |
| 110 | + """ |
| 111 | + |
| 112 | + let newBody: ExprSyntax = |
| 113 | + """ |
| 114 | +
|
| 115 | + \(raw: isResultReturn ? "try await withCheckedThrowingContinuation { continuation in" : "await withCheckedContinuation { continuation in") |
| 116 | + \(raw: funcDecl.name)(\(raw: callArguments.joined(separator: ", "))) { \(raw: returnType != nil ? "returnValue in" : "") |
| 117 | +
|
| 118 | + \(raw: isResultReturn ? switchBody : "continuation.resume(returning: \(raw: returnType != nil ? "returnValue" : "()"))") |
| 119 | +
|
| 120 | + } |
| 121 | + } |
| 122 | +
|
| 123 | + """ |
| 124 | + |
| 125 | + let newFunc = |
| 126 | + funcDecl |
| 127 | + .with( |
| 128 | + \.signature, |
| 129 | + funcDecl.signature |
| 130 | + .with( |
| 131 | + \.effectSpecifiers, |
| 132 | + FunctionEffectSpecifiersSyntax( |
| 133 | + leadingTrivia: .space, |
| 134 | + asyncSpecifier: .keyword(.async), |
| 135 | + throwsSpecifier: isResultReturn ? .keyword(.throws) : nil |
| 136 | + ) // add async |
| 137 | + ) |
| 138 | + .with( |
| 139 | + \.returnClause, |
| 140 | + successReturnType != nil ? ReturnClauseSyntax(leadingTrivia: .space, type: successReturnType!.with(\.leadingTrivia, .space)) : nil |
| 141 | + ) // add result type |
| 142 | + .with( |
| 143 | + \.parameterClause, |
| 144 | + funcDecl.signature.parameterClause.with(\.parameters, newParameterList) // drop completion handler |
| 145 | + .with(\.trailingTrivia, []) |
| 146 | + ) |
| 147 | + ) |
| 148 | + .with( |
| 149 | + \.body, |
| 150 | + CodeBlockSyntax( |
| 151 | + leftBrace: .leftBraceToken(leadingTrivia: .space), |
| 152 | + statements: CodeBlockItemListSyntax( |
| 153 | + [CodeBlockItemSyntax(item: .expr(newBody))] |
| 154 | + ), |
| 155 | + rightBrace: .rightBraceToken(leadingTrivia: .newline) |
| 156 | + ) |
| 157 | + ) |
| 158 | + .with(\.attributes, newAttributeList) |
| 159 | + .with(\.leadingTrivia, .newlines(2)) |
| 160 | + |
| 161 | + return [DeclSyntax(newFunc)] |
| 162 | + } |
| 163 | +} |
0 commit comments