|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2022-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 | +import SwiftDiagnostics |
| 16 | + |
| 17 | +/// Macro implementing the TaskLocal functionality. |
| 18 | +/// |
| 19 | +/// It introduces a peer `static let $name: TaskLocal<Type>` as well as a getter |
| 20 | +/// that accesses the task local storage. |
| 21 | +public enum TaskLocalMacro {} |
| 22 | + |
| 23 | +extension TaskLocalMacro: PeerMacro { |
| 24 | + public static func expansion( |
| 25 | + of node: AttributeSyntax, |
| 26 | + providingPeersOf declaration: some DeclSyntaxProtocol, |
| 27 | + in context: some MacroExpansionContext |
| 28 | + ) throws -> [DeclSyntax] { |
| 29 | + guard let varDecl = try requireVar(declaration, diagnose: false) else { |
| 30 | + return [] |
| 31 | + } |
| 32 | + guard try requireStaticContext(varDecl, in: context, diagnose: false) else { |
| 33 | + return [] |
| 34 | + } |
| 35 | + |
| 36 | + guard varDecl.bindings.count == 1 else { |
| 37 | + throw DiagnosticsError( |
| 38 | + syntax: declaration, |
| 39 | + message: "'@TaskLocal' property must have exactly one binding", id: .incompatibleDecl) |
| 40 | + } |
| 41 | + guard let firstBinding = varDecl.bindings.first else { |
| 42 | + throw DiagnosticsError( |
| 43 | + syntax: declaration, |
| 44 | + message: "'@TaskLocal' property must have declared binding", id: .incompatibleDecl) |
| 45 | + } |
| 46 | + |
| 47 | + guard let name = firstBinding.pattern.as(IdentifierPatternSyntax.self)?.identifier else { |
| 48 | + throw DiagnosticsError( |
| 49 | + syntax: declaration, |
| 50 | + message: "'@TaskLocal' property must have name", id: .incompatibleDecl) |
| 51 | + } |
| 52 | + |
| 53 | + let type = firstBinding.typeAnnotation?.type |
| 54 | + let explicitTypeAnnotation: TypeAnnotationSyntax? |
| 55 | + if let type { |
| 56 | + explicitTypeAnnotation = TypeAnnotationSyntax(type: TypeSyntax("TaskLocal<\(type.trimmed)>")) |
| 57 | + } else { |
| 58 | + explicitTypeAnnotation = nil |
| 59 | + } |
| 60 | + |
| 61 | + let initialValue: ExprSyntax |
| 62 | + if let initializerValue = firstBinding.initializer?.value { |
| 63 | + initialValue = ExprSyntax(initializerValue) |
| 64 | + } else if let type, type.isOptional { |
| 65 | + initialValue = ExprSyntax(NilLiteralExprSyntax()) |
| 66 | + } else { |
| 67 | + throw DiagnosticsError( |
| 68 | + syntax: declaration, |
| 69 | + message: "'@TaskLocal' property must have default value, or be optional", id: .mustBeVar) |
| 70 | + } |
| 71 | + |
| 72 | + // If the property is global, do not prefix the synthesised decl with 'static' |
| 73 | + let isGlobal = context.lexicalContext.isEmpty |
| 74 | + let staticKeyword: TokenSyntax? |
| 75 | + if isGlobal { |
| 76 | + staticKeyword = nil |
| 77 | + } else { |
| 78 | + staticKeyword = TokenSyntax.keyword(.static, trailingTrivia: .space) |
| 79 | + } |
| 80 | + |
| 81 | + return [ |
| 82 | + """ |
| 83 | + \(staticKeyword)let $\(name)\(explicitTypeAnnotation) = TaskLocal(wrappedValue: \(initialValue)) |
| 84 | + """ |
| 85 | + ] |
| 86 | + } |
| 87 | +} |
| 88 | + |
| 89 | +extension TaskLocalMacro: AccessorMacro { |
| 90 | + public static func expansion( |
| 91 | + of node: AttributeSyntax, |
| 92 | + providingAccessorsOf declaration: some DeclSyntaxProtocol, |
| 93 | + in context: some MacroExpansionContext |
| 94 | + ) throws -> [AccessorDeclSyntax] { |
| 95 | + // We very specifically have to fail and diagnose in the accessor macro, |
| 96 | + // rather than in the peer macro, since returning [] from the accessor |
| 97 | + // macro adds another series of errors about it missing to emit a decl. |
| 98 | + guard let varDecl = try requireVar(declaration) else { |
| 99 | + return [] |
| 100 | + } |
| 101 | + try requireStaticContext(varDecl, in: context) |
| 102 | + |
| 103 | + guard let firstBinding = varDecl.bindings.first else { |
| 104 | + return [] |
| 105 | + } |
| 106 | + |
| 107 | + guard let name = firstBinding.pattern.as(IdentifierPatternSyntax.self)?.identifier else { |
| 108 | + return [] |
| 109 | + } |
| 110 | + |
| 111 | + return ["get { $\(name).get() }"] |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +@discardableResult |
| 116 | +private func requireVar(_ decl: some DeclSyntaxProtocol, |
| 117 | + diagnose: Bool = true) throws -> VariableDeclSyntax? { |
| 118 | + if let varDecl = decl.as(VariableDeclSyntax.self) { |
| 119 | + return varDecl |
| 120 | + } |
| 121 | + if diagnose { |
| 122 | + throw DiagnosticsError( |
| 123 | + syntax: decl, |
| 124 | + message: "'@TaskLocal' can only be applied to properties", id: .mustBeVar) |
| 125 | + } |
| 126 | + |
| 127 | + return nil |
| 128 | +} |
| 129 | + |
| 130 | +@discardableResult |
| 131 | +private func requireStaticContext(_ decl: VariableDeclSyntax, |
| 132 | + in context: some MacroExpansionContext, |
| 133 | + diagnose: Bool = true) throws -> Bool { |
| 134 | + let isStatic = decl.modifiers.contains { modifier in |
| 135 | + modifier.name.text == "\(Keyword.static)" |
| 136 | + } |
| 137 | + |
| 138 | + if isStatic { |
| 139 | + return true |
| 140 | + } |
| 141 | + |
| 142 | + let isGlobal = context.lexicalContext.isEmpty |
| 143 | + if isGlobal { |
| 144 | + return true |
| 145 | + } |
| 146 | + |
| 147 | + if diagnose { |
| 148 | + throw DiagnosticsError( |
| 149 | + syntax: decl, |
| 150 | + message: "'@TaskLocal' can only be applied to 'static' property, or global variables", id: .mustBeStatic) |
| 151 | + } |
| 152 | + |
| 153 | + return false |
| 154 | +} |
| 155 | + |
| 156 | +extension TypeSyntax { |
| 157 | + // This isn't great since we can't handle type aliases since the macro |
| 158 | + // has no type information, but at least for the common case for Optional<T> |
| 159 | + // and T? we can detect the optional. |
| 160 | + fileprivate var isOptional: Bool { |
| 161 | + switch self.as(TypeSyntaxEnum.self) { |
| 162 | + case .optionalType: |
| 163 | + return true |
| 164 | + case .identifierType(let identifierType): |
| 165 | + return identifierType.name.text == "Optional" |
| 166 | + case .memberType(let memberType): |
| 167 | + guard let baseIdentifier = memberType.baseType.as(IdentifierTypeSyntax.self), |
| 168 | + baseIdentifier.name.text == "Swift" else { |
| 169 | + return false |
| 170 | + } |
| 171 | + return memberType.name.text == "Optional" |
| 172 | + default: return false |
| 173 | + } |
| 174 | + } |
| 175 | +} |
| 176 | + |
| 177 | +struct TaskLocalMacroDiagnostic: DiagnosticMessage { |
| 178 | + enum ID: String { |
| 179 | + case mustBeVar = "must be var" |
| 180 | + case mustBeStatic = "must be static" |
| 181 | + case incompatibleDecl = "incompatible declaration" |
| 182 | + } |
| 183 | + |
| 184 | + var message: String |
| 185 | + var diagnosticID: MessageID |
| 186 | + var severity: DiagnosticSeverity |
| 187 | + |
| 188 | + init(message: String, diagnosticID: SwiftDiagnostics.MessageID, severity: SwiftDiagnostics.DiagnosticSeverity = .error) { |
| 189 | + self.message = message |
| 190 | + self.diagnosticID = diagnosticID |
| 191 | + self.severity = severity |
| 192 | + } |
| 193 | + |
| 194 | + init(message: String, domain: String, id: ID, severity: SwiftDiagnostics.DiagnosticSeverity = .error) { |
| 195 | + self.message = message |
| 196 | + self.diagnosticID = MessageID(domain: domain, id: id.rawValue) |
| 197 | + self.severity = severity |
| 198 | + } |
| 199 | +} |
| 200 | + |
| 201 | +extension DiagnosticsError { |
| 202 | + init( |
| 203 | + syntax: some SyntaxProtocol, |
| 204 | + message: String, |
| 205 | + domain: String = "Swift", |
| 206 | + id: TaskLocalMacroDiagnostic.ID, |
| 207 | + severity: SwiftDiagnostics.DiagnosticSeverity = .error) { |
| 208 | + self.init(diagnostics: [ |
| 209 | + Diagnostic( |
| 210 | + node: Syntax(syntax), |
| 211 | + message: TaskLocalMacroDiagnostic( |
| 212 | + message: message, |
| 213 | + domain: domain, |
| 214 | + id: id, |
| 215 | + severity: severity)) |
| 216 | + ]) |
| 217 | + } |
| 218 | +} |
0 commit comments