Skip to content

Add SyntaxEnum per base syntax kind #2351

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 2 commits into from
Nov 13, 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 @@ -57,4 +57,50 @@ let syntaxEnumFile = SourceFileSyntax(leadingTrivia: copyrightHeader) {
}
}
}

for base in SYNTAX_NODES where base.kind.isBase {
let baseKind = base.kind
let baseName = baseKind.rawValue.withFirstCharacterUppercased;
let enumType: TypeSyntax = "\(raw: baseName)SyntaxEnum"

try! EnumDeclSyntax(
"""
/// Enum to exhaustively switch over all different \(raw: baseName) syntax nodes.
public enum \(enumType)
"""
) {
for node in NON_BASE_SYNTAX_NODES where node.base == baseKind {
DeclSyntax(
"""
\(node.apiAttributes())\
case \(node.varOrCaseName)(\(node.kind.syntaxType))
"""
)
}
}

try! ExtensionDeclSyntax(
"""
public extension \(baseKind.syntaxType)
"""
) {
try FunctionDeclSyntax(
"""
/// Get an enum that can be used to exhaustively switch over all \(raw: baseName) syntax nodes.
func `as`(_: \(enumType).Type) -> \(enumType)
"""
) {
try SwitchExprSyntax("switch raw.kind") {
for node in NON_BASE_SYNTAX_NODES where node.base == baseKind {
SwitchCaseSyntax("case .\(node.varOrCaseName):") {
StmtSyntax("return .\(node.varOrCaseName)(\(node.kind.syntaxType)(self)!)")
}
}
SwitchCaseSyntax("default:") {
ExprSyntax(#"preconditionFailure("unknown \#(raw: baseName) syntax kind")"#)
}
}
}
}
}
}
4 changes: 4 additions & 0 deletions Release Notes/511.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@
- Issue: https://github.com/apple/swift-syntax/issues/2015
- Pull Request: https://github.com/apple/swift-syntax/pull/2021

- `DeclSyntaxEnum`, `StmtSyntaxEnum`, `ExprSyntaxEnum`, `TypeSyntaxEnum`, and `PatternSyntaxEnum`
- Description: Enum to exhaustively switch over all different syntax nodes of each base type.
- Pull Request: https://github.com/apple/swift-syntax/pull/2351

## API Behavior Changes

## Deprecations
Expand Down
Loading