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
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftSyntax
import SwiftSyntaxBuilder
import SyntaxSupport
import Utils
let syntaxBaseNodesFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
for node in SYNTAX_NODES where node.kind.isBase {
let documentation = SwiftSyntax.Trivia(joining: [
node.documentation,
node.subtypes,
])
DeclSyntax(
"""
// MARK: - \(node.kind.syntaxType)
/// Protocol to which all \(raw: node.kind.doccLink) nodes conform.
///
/// Extension point to add common methods to all \(raw: node.kind.doccLink) nodes.
///
/// - Warning: Do not conform to this protocol yourself.
\(node.apiAttributes())\
public protocol \(node.kind.protocolType): \(node.base.protocolType) {}
"""
)
DeclSyntax(
#"""
/// Extension of ``\#(node.kind.protocolType)`` to provide casting methods.
///
/// These methods enable casting between syntax node types within the same
/// base node protocol hierarchy (e.g., ``DeclSyntaxProtocol``).
///
/// While ``SyntaxProtocol`` offers general casting methods (``SyntaxProtocol.as(_:)``,
/// ``SyntaxProtocol.is(_:)``, and ``SyntaxProtocol.cast(_:)``), these often aren't
/// appropriate for use on types conforming to a specific base node protocol
/// like ``\#(node.kind.protocolType)``. That's because at this level,
/// we know that the cast to another base node type (e.g., ``DeclSyntaxProtocol``
/// when working with ``ExprSyntaxProtocol``) is guaranteed to fail.
///
/// To guide developers toward correct usage, this extension provides overloads
/// of these casting methods that are restricted to the same base node type.
/// Furthermore, it marks the inherited casting methods from ``SyntaxProtocol`` as
/// deprecated, indicating that they will always fail when used in this context.
extension \#(node.kind.protocolType) {
/// Checks if the current syntax node can be cast to a given specialized syntax type.
///
/// - Returns: `true` if the node can be cast, `false` otherwise.
public func `is`<S: \#(node.kind.protocolType)>(_ syntaxType: S.Type) -> Bool {
return self.as(syntaxType) != nil
}
/// Attempts to cast the current syntax node to a given specialized syntax type.
///
/// - Returns: An instance of the specialized type, or `nil` if the cast fails.
public func `as`<S: \#(node.kind.protocolType)>(_ syntaxType: S.Type) -> S? {
return S.init(self)
}
/// Force-casts the current syntax node to a given specialized syntax type.
///
/// - Returns: An instance of the specialized type.
///
/// - Warning: This function will crash if the cast is not possible. Use `as` to safely attempt a cast.
public func cast<S: \#(node.kind.protocolType)>(_ syntaxType: S.Type) -> S {
return self.as(S.self)!
}
/// Checks if the current syntax node can be upcast to its base node type (\#(raw: node.kind.doccLink)).
///
/// - Returns: `true` since the node can always be upcast to its base node.
@available(*, deprecated, message: "This cast will always succeed")
public func `is`(_ syntaxType: \#(node.kind.syntaxType).Type) -> Bool {
return true
}
/// Attempts to upcast the current syntax node to its base node type (\#(raw: node.kind.doccLink)).
///
/// - Returns: The base node created from the current syntax node, as the node can always be upcast to its base type.
@available(*, deprecated, message: "Use `\#(node.kind.syntaxType).init` for upcasting")
public func `as`(_ syntaxType: \#(node.kind.syntaxType).Type) -> \#(node.kind.syntaxType)? {
return \#(node.kind.syntaxType)(self)
}
/// Force-upcast the current syntax node to its base node type (\#(raw: node.kind.doccLink)).
///
/// - Returns: The base node created from the current syntax node, as the node can always be upcast to its base type.
@available(*, deprecated, message: "Use `\#(node.kind.syntaxType).init` for upcasting")
public func cast(_ syntaxType: \#(node.kind.syntaxType).Type) -> \#(node.kind.syntaxType) {
return \#(node.kind.syntaxType)(self)
}
/// Checks if the current syntax node can be cast to a given node type from a base node protocol hierarchy other
/// than ``\#(node.kind.protocolType)``.
///
/// - Returns: `true` if the node can be cast, `false` otherwise.
///
/// - Note: In most cases, this is comparing a ``\#(node.kind.protocolType)`` to a node that is not a
/// ``\#(node.kind.protocolType)``, which will always fail. If the `syntaxType` argument is a generic type,
/// constrain it to ``\#(node.kind.protocolType)`` instead of ``SyntaxProtocol``.
@available(*, deprecated, message: "Type argument should be part of the '\#(node.kind.protocolType)' hierarchy")
public func `is`<S: SyntaxProtocol>(_ syntaxType: S.Type) -> Bool {
return self.as(syntaxType) != nil
}
/// Attempts to cast the current syntax node to a given node type from the a base node protocol hierarchy other than
/// ``\#(node.kind.protocolType)``.
///
/// - Returns: An instance of the specialized type, or `nil` if the cast fails.
///
/// - Note: In most cases, this is casting a ``\#(node.kind.protocolType)`` to a node that is not a
/// ``\#(node.kind.protocolType)``, which will always fail. If the `syntaxType` argument is a generic type,
/// constrain it to ``\#(node.kind.protocolType)`` instead of ``SyntaxProtocol``.
@available(*, deprecated, message: "Type argument should be part of the '\#(node.kind.protocolType)' hierarchy")
public func `as`<S: SyntaxProtocol>(_ syntaxType: S.Type) -> S? {
return S.init(self)
}
/// Force-casts the current syntax node to a given node type from a base node protocol hierarchy other than
/// ``\#(node.kind.protocolType)``.
///
/// - Returns: An instance of the specialized type.
///
/// - Warning: This function will crash if the cast is not possible. Use `as` to safely attempt a cast.
///
/// - Note: In most cases, this is casting a ``\#(node.kind.protocolType)`` to a node that is not a
/// ``\#(node.kind.protocolType)``, which will always fail. If the `syntaxType` argument is a generic type,
/// constrain it to ``\#(node.kind.protocolType)`` instead of ``SyntaxProtocol``.
@available(*, deprecated, message: "Type argument should be part of the '\#(node.kind.protocolType)' hierarchy")
public func cast<S: SyntaxProtocol>(_ syntaxType: S.Type) -> S {
return self.as(S.self)!
}
}
"""#
)
try! ExtensionDeclSyntax("extension Syntax") {
DeclSyntax(
"""
/// Check whether the non-type erased version of this syntax node conforms to
/// \(node.kind.protocolType).
///
/// - Note: This will incur an existential conversion.
public func isProtocol(_: \(node.kind.protocolType).Protocol) -> Bool {
return self.asProtocol(\(node.kind.protocolType).self) != nil
}
"""
)
DeclSyntax(
"""
/// Return the non-type erased version of this syntax node if it conforms to
/// \(node.kind.protocolType). Otherwise return nil.
///
/// - Note: This will incur an existential conversion.
public func asProtocol(_: \(node.kind.protocolType).Protocol) -> \(node.kind.protocolType)? {
return self.asProtocol(SyntaxProtocol.self) as? \(node.kind.protocolType)
}
"""
)
}
try! StructDeclSyntax(
"""
\(documentation)\
\(node.apiAttributes())\
public struct \(node.kind.syntaxType): \(node.kind.protocolType), SyntaxHashable
"""
) {
DeclSyntax("public let _syntaxNode: Syntax")
DeclSyntax(
"""
/// Create a \(raw: node.kind.doccLink) node from a specialized syntax node.
public init(_ syntax: __shared some \(node.kind.protocolType)) {
// We know this cast is going to succeed. Go through init(_: SyntaxData)
// to do a sanity check and verify the kind matches in debug builds and get
// maximum performance in release builds.
self = Syntax(syntax).cast(Self.self)
}
"""
)
DeclSyntax(
"""
/// Create a \(raw: node.kind.doccLink) node from a specialized optional syntax node.
public init?(_ syntax: __shared (some \(node.kind.protocolType))?) {
guard let syntax = syntax else { return nil }
self.init(syntax)
}
"""
)
DeclSyntax(
"""
public init(fromProtocol syntax: __shared \(node.kind.protocolType)) {
// We know this cast is going to succeed. Go through init(_: SyntaxData)
// to do a sanity check and verify the kind matches in debug builds and get
// maximum performance in release builds.
self = Syntax(syntax).cast(Self.self)
}
"""
)
DeclSyntax(
"""
/// Create a \(raw: node.kind.doccLink) node from a specialized optional syntax node.
public init?(fromProtocol syntax: __shared \(node.kind.protocolType)?) {
guard let syntax = syntax else { return nil }
self.init(fromProtocol: syntax)
}
"""
)
try InitializerDeclSyntax("public init?(_ node: __shared some SyntaxProtocol)") {
try SwitchExprSyntax("switch node.raw.kind") {
SwitchCaseListSyntax {
SwitchCaseSyntax(
label: .case(
SwitchCaseLabelSyntax {
for childNode in SYNTAX_NODES where childNode.base == node.kind {
SwitchCaseItemSyntax(
pattern: ExpressionPatternSyntax(
expression: ExprSyntax(".\(childNode.varOrCaseName)")
)
)
}
}
)
) {
ExprSyntax("self._syntaxNode = node._syntaxNode")
}
SwitchCaseSyntax("default:") {
StmtSyntax("return nil")
}
}
}
}
DeclSyntax(
"""
/// Syntax nodes always conform to `\(node.kind.protocolType)`. This API is just
/// added for consistency.
///
/// - Note: This will incur an existential conversion.
@available(*, deprecated, message: "Expression always evaluates to true")
public func isProtocol(_: \(node.kind.protocolType).Protocol) -> Bool {
return true
}
"""
)
DeclSyntax(
"""
/// Return the non-type erased version of this syntax node.
///
/// - Note: This will incur an existential conversion.
public func asProtocol(_: \(node.kind.protocolType).Protocol) -> \(node.kind.protocolType) {
return Syntax(self).asProtocol(\(node.kind.protocolType).self)!
}
"""
)
try VariableDeclSyntax("public static var structure: SyntaxNodeStructure") {
let choices = ArrayExprSyntax {
for childNode in SYNTAX_NODES where childNode.base == node.kind {
ArrayElementSyntax(
leadingTrivia: .newline,
expression: ExprSyntax(".node(\(childNode.kind.syntaxType).self)")
)
}
}
StmtSyntax("return .choices(\(choices))")
}
}
leafProtocolDecl(type: node.kind.leafProtocolType, inheritedType: node.kind.protocolType)
leafProtocolExtension(type: node.kind.leafProtocolType, inheritedType: node.kind.protocolType)
}
try! ExtensionDeclSyntax(
"""
// MARK: - Syntax
extension Syntax
"""
) {
try VariableDeclSyntax("public static var structure: SyntaxNodeStructure") {
let choices = ArrayExprSyntax {
ArrayElementSyntax(
leadingTrivia: .newline,
expression: ExprSyntax(".node(TokenSyntax.self)")
)
for node in NON_BASE_SYNTAX_NODES {
ArrayElementSyntax(
leadingTrivia: .newline,
expression: ExprSyntax(".node(\(node.kind.syntaxType).self)")
)
}
}
StmtSyntax("return .choices(\(choices))")
}
}
leafProtocolDecl(type: "_LeafSyntaxNodeProtocol", inheritedType: "SyntaxProtocol")
leafProtocolExtension(type: "_LeafSyntaxNodeProtocol", inheritedType: "SyntaxProtocol")
}
private func leafProtocolDecl(type: TypeSyntax, inheritedType: TypeSyntax) -> DeclSyntax {
DeclSyntax(
"""
/// Protocol that syntax nodes conform to if they don't have any semantic subtypes.
/// These are syntax nodes that are not considered base nodes for other syntax types.
///
/// Syntax nodes conforming to this protocol have their inherited casting methods
/// deprecated to prevent incorrect casting.
public protocol \(type): \(inheritedType) {}
"""
)
}
private func leafProtocolExtension(type: TypeSyntax, inheritedType: TypeSyntax) -> DeclSyntax {
DeclSyntax(
#"""
extension \#(type) {
/// Checks if the current leaf syntax node can be cast to a different specified type.
///
/// - Returns: `false` since the leaf node cannot be cast to a different specified type.
///
/// - Note: This method overloads the general `is` method and is marked as deprecated to produce a warning,
/// informing the user that the cast will always fail.
@available(*, deprecated, message: "This cast will always fail")
public func `is`<S: \#(inheritedType)>(_ syntaxType: S.Type) -> Bool {
return false
}
/// Attempts to cast the current leaf syntax node to a different specified type.
///
/// - Returns: `nil` since the leaf node cannot be cast to a different specified type.
///
/// - Note: This method overloads the general `as` method and is marked as deprecated to produce a warning,
/// informing the user that the cast will always fail.
@available(*, deprecated, message: "This cast will always fail")
public func `as`<S: \#(inheritedType)>(_ syntaxType: S.Type) -> S? {
return nil
}
/// Force-casts the current leaf syntax node to a different specified type.
///
/// - Returns: This method will always trigger a runtime crash and never return.
///
/// - Note: This method overloads the general `cast` method and is marked as deprecated to produce a warning,
/// informing the user that the cast will always fail.
/// - Warning: Invoking this method will lead to a fatal error.
@available(*, deprecated, message: "This cast will always fail")
public func cast<S: \#(inheritedType)>(_ syntaxType: S.Type) -> S {
fatalError("\(Self.self) cannot be cast to \(S.self)")
}
}
"""#
)
}
|