Skip to content

Prevent Unrelated Casts on Child Choice Node #2184

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,11 @@ let syntaxCollectionsFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {

StmtSyntax("return .choices(\(choices))")
}

for choiceNodeName in node.elementChoices {
let choiceNode = SYNTAX_NODE_MAP[choiceNodeName]!
choiceNodeCastingMethods(for: choiceNode.kind)
}
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
//===----------------------------------------------------------------------===//
//
// 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

@MemberBlockItemListBuilder
func choiceNodeCastingMethods(for syntaxNodeKind: SyntaxNodeKind) -> MemberBlockItemListSyntax {
if syntaxNodeKind.isBase {
DeclSyntax(
"""
/// Checks if the current syntax node can be cast to the type conforming to the ``\(syntaxNodeKind.protocolType)`` protocol.
///
/// - Returns: `true` if the node can be cast, `false` otherwise.
public func `is`<S: \(syntaxNodeKind.protocolType)>(_ syntaxType: S.Type) -> Bool {
return self.as(syntaxType) != nil
}
"""
)

DeclSyntax(
"""
/// Attempts to cast the current syntax node to the type conforming to the ``\(syntaxNodeKind.protocolType)`` protocol.
///
/// - Returns: An instance of the specialized type, or `nil` if the cast fails.
public func `as`<S: \(syntaxNodeKind.protocolType)>(_ syntaxType: S.Type) -> S? {
return S.init(self)
}
"""
)

DeclSyntax(
"""
/// Force-casts the current syntax node to the type conforming to the ``\(syntaxNodeKind.protocolType)`` protocol.
///
/// - 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: \(syntaxNodeKind.protocolType)>(_ syntaxType: S.Type) -> S {
return self.as(S.self)!
}
"""
)
} else {
DeclSyntax(
"""
/// Checks if the current syntax node can be cast to ``\(syntaxNodeKind.syntaxType)``.
///
/// - Returns: `true` if the node can be cast, `false` otherwise.
public func `is`(_ syntaxType: \(syntaxNodeKind.syntaxType).Type) -> Bool {
return self.as(syntaxType) != nil
}
"""
)

DeclSyntax(
"""
/// Attempts to cast the current syntax node to ``\(syntaxNodeKind.syntaxType)``.
///
/// - Returns: An instance of ``\(syntaxNodeKind.syntaxType)``, or `nil` if the cast fails.
public func `as`(_ syntaxType: \(syntaxNodeKind.syntaxType).Type) -> \(syntaxNodeKind.syntaxType)? {
return \(syntaxNodeKind.syntaxType).init(self)
}
"""
)

DeclSyntax(
"""
/// Force-casts the current syntax node to ``\(syntaxNodeKind.syntaxType)``.
///
/// - Returns: An instance of ``\(syntaxNodeKind.syntaxType)``.
/// - Warning: This function will crash if the cast is not possible. Use `as` to safely attempt a cast.
public func cast(_ syntaxType: \(syntaxNodeKind.syntaxType).Type) -> \(syntaxNodeKind.syntaxType) {
return self.as(\(syntaxNodeKind.syntaxType).self)!
}
"""
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -289,5 +289,9 @@ private func generateSyntaxChildChoices(for child: Child) throws -> EnumDeclSynt

StmtSyntax("return .choices(\(choices))")
}

for choiceNode in choices {
choiceNodeCastingMethods(for: choiceNode.syntaxNodeKind)
}
}
}
8 changes: 8 additions & 0 deletions Release Notes/510.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@
- `SyntaxStringInterpolation.appendInterpolation(_: (some SyntaxProtocol)?)`
- Description: Allows optional syntax nodes to be used inside string interpolation of syntax nodes. If the node is `nil`, nothing will get added to the string interpolation.
- Pull Request: https://github.com/apple/swift-syntax/pull/2085

- `SyntaxCollection.index(at:)`
- Description: Returns the index of the n-th element in a `SyntaxCollection`. This computation is in O(n) and `SyntaxCollection` is not subscriptable by an integer.
- Pull Request: https://github.com/apple/swift-syntax/pull/2014

- Convenience initializer `ClosureCaptureSyntax.init()`
- Description: Provides a convenience initializer for `ClosureCaptureSyntax` that takes a concrete `name` argument and automatically adds `equal = TokenSyntax.equalToken()` to it.
- Issue: https://github.com/apple/swift-syntax/issues/1984
- Pull Request: https://github.com/apple/swift-syntax/pull/2127

- Convenience initializer `EnumCaseParameterSyntax.init()`
- Description: Provides a convenience initializer for `EnumCaseParameterSyntax` that takes a concrete `firstName` value and adds `colon = TokenSyntax.colonToken()` automatically to it.
- Issue: https://github.com/apple/swift-syntax/issues/1984
Expand Down Expand Up @@ -49,6 +52,11 @@
- Description: `is`, `as`, and `cast` methods on base node protocols with base-type conversions are marked as deprecated. The deprecated methods emit a warning that informs the developer that the cast will always succeed and should be done using the base node's initializer.
- Issue: https://github.com/apple/swift-syntax/issues/2092
- Pull Request: https://github.com/apple/swift-syntax/pull/2108

- Child Choice Node Casts
- Description: `is`, `as`, and `cast` methods for types not contained in the choice node are marked as deprecated. The deprecated methods will emit a warning, indicating that the cast will always fail.
- Issue: https://github.com/apple/swift-syntax/issues/2092
- Pull Request: https://github.com/apple/swift-syntax/pull/2184

## API-Incompatible Changes

Expand Down
35 changes: 35 additions & 0 deletions Sources/SwiftSyntax/SyntaxProtocol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -698,3 +698,38 @@ public extension SyntaxProtocol {
/// Protocol for the enums nested inside ``Syntax`` nodes that enumerate all the
/// possible types a child node might have.
public protocol SyntaxChildChoices: SyntaxProtocol {}

public extension SyntaxChildChoices {

/// Checks if the current ``SyntaxChildChoices`` instance can be cast to a given specialized syntax type.
///
/// - Returns: `true` if the node can be cast, `false` otherwise.
///
/// - Note: This method is marked as deprecated because it is advised not to use it for unrelated casts.
@available(*, deprecated, message: "This cast will always fail")
func `is`<S: SyntaxProtocol>(_ syntaxType: S.Type) -> Bool {
return self.as(syntaxType) != nil
}

/// Attempts to cast the current ``SyntaxChildChoices`` instance to a given specialized syntax type.
///
/// - Returns: An instance of the specialized syntax type, or `nil` if the cast fails.
///
/// - Note: This method is marked as deprecated because it is advised not to use it for unrelated casts.
@available(*, deprecated, message: "This cast will always fail")
func `as`<S: SyntaxProtocol>(_ syntaxType: S.Type) -> S? {
return S.init(self)
}

/// Force-casts the current ``SyntaxChildChoices`` instance to a given specialized syntax type.
///
/// - Returns: An instance of the specialized syntax type.
///
/// - Warning: This function will crash if the cast is not possible. Use `as` for a safe attempt.
///
/// - Note: This method is marked as deprecated because it is advised not to use it for unrelated casts.
@available(*, deprecated, message: "This cast will always fail")
func cast<S: SyntaxProtocol>(_ syntaxType: S.Type) -> S {
return self.as(S.self)!
}
}
Loading