swift-syntax
A set of Swift libraries for parsing, inspecting, generating, and transforming Swift source code.
Top Related Projects
The Swift Programming Language
A tool to enforce Swift style and conventions.
This maintains proposals for changes and user-visible enhancements to the Swift Programming Language.
The Package Manager for the Swift Programming Language
Language Server Protocol implementation for Swift and C-based languages
Quick Overview
Swift Syntax is a set of Swift libraries for parsing, inspecting, generating, and transforming Swift source code. It provides a robust foundation for building Swift tooling, including code formatters, linters, and source code analysis tools. The project is an integral part of the Swift ecosystem and is maintained by the Swift project.
Pros
- Provides a powerful and flexible API for working with Swift source code
- Officially maintained by the Swift project, ensuring compatibility and regular updates
- Supports both parsing and generating Swift code, enabling a wide range of use cases
- Offers high performance and efficiency, suitable for large-scale code analysis
Cons
- Steep learning curve due to the complexity of the API and Swift language intricacies
- Documentation can be sparse in some areas, requiring users to explore the source code
- Limited support for older Swift versions, as it focuses on the latest language features
- May require frequent updates to keep up with Swift language evolution
Code Examples
- Parsing Swift source code:
import SwiftSyntax
import SwiftParser
let source = "func greet(_ name: String) { print(\"Hello, \\(name)!\") }"
let sourceFile = Parser.parse(source: source)
print(sourceFile.description)
- Traversing the syntax tree:
import SwiftSyntax
class FunctionVisitor: SyntaxVisitor {
override func visit(_ node: FunctionDeclSyntax) -> SyntaxVisitorContinueKind {
print("Found function: \(node.identifier)")
return .visitChildren
}
}
let visitor = FunctionVisitor()
visitor.walk(sourceFile)
- Modifying syntax:
import SwiftSyntax
let modified = sourceFile.withLeadingTrivia(.spaces(4))
print(modified.description)
Getting Started
To use Swift Syntax in your project, add it as a dependency in your Package.swift
file:
dependencies: [
.package(url: "https://github.com/apple/swift-syntax.git", from: "509.0.0")
],
targets: [
.target(
name: "YourTarget",
dependencies: [
.product(name: "SwiftSyntax", package: "swift-syntax"),
.product(name: "SwiftParser", package: "swift-syntax"),
]
)
]
Then, import the necessary modules in your Swift files:
import SwiftSyntax
import SwiftParser
You can now use the Swift Syntax API to parse, analyze, and transform Swift code in your project.
Competitor Comparisons
The Swift Programming Language
Pros of Swift
- Comprehensive repository containing the entire Swift programming language
- Includes compiler, standard library, and core components
- Provides deeper access to Swift's internals and development process
Cons of Swift
- Larger and more complex codebase, potentially harder to navigate
- Requires more setup and resources to build and contribute
- May be overwhelming for those only interested in syntax-related features
Code Comparison
Swift (compiler implementation):
func parseTopLevelDecl() -> Decl {
switch tok.kind {
case .kw_func:
return parseFuncDecl()
case .kw_var, .kw_let:
return parseVarDecl()
default:
diagnose(.expectedDeclaration)
return makeParserErrorDecl()
}
}
Swift-syntax (syntax tree representation):
struct FunctionDeclSyntax: DeclSyntaxProtocol {
var funcKeyword: TokenSyntax
var identifier: TokenSyntax
var genericParameterClause: GenericParameterClauseSyntax?
var signature: FunctionSignatureSyntax
var body: CodeBlockSyntax?
}
Swift-syntax focuses specifically on Swift's syntax representation and parsing, making it more suitable for tasks like source code analysis and transformation. Swift, on the other hand, provides a complete implementation of the language, including the compiler and runtime components, offering a broader scope but with increased complexity.
A tool to enforce Swift style and conventions.
Pros of SwiftLint
- Easier to set up and use for basic linting tasks
- Provides a comprehensive set of pre-defined rules
- Integrates well with Xcode and CI/CD pipelines
Cons of SwiftLint
- Less flexible for creating custom rules
- May not cover all advanced Swift syntax features
- Can be slower for large codebases due to its design
Code Comparison
SwiftLint configuration:
disabled_rules:
- trailing_whitespace
opt_in_rules:
- empty_count
- missing_docs
swift-syntax usage:
import SwiftSyntax
import SwiftSyntaxParser
let sourceFile = try SyntaxParser.parse(source: "let x = 5")
let visitor = MyCustomVisitor()
visitor.walk(sourceFile)
Summary
SwiftLint is a popular linting tool for Swift, offering ease of use and a wide range of pre-defined rules. It's great for teams looking for quick setup and standard code style enforcement. On the other hand, swift-syntax provides a more powerful and flexible foundation for creating custom Swift tools, including linters. While it requires more setup and coding, swift-syntax offers greater control and the ability to work with advanced Swift syntax features. The choice between the two depends on the specific needs of the project and the team's expertise in Swift tooling.
This maintains proposals for changes and user-visible enhancements to the Swift Programming Language.
Pros of swift-evolution
- Focuses on the Swift language evolution process, providing a centralized place for proposals and discussions
- Offers a comprehensive view of Swift's development history and future direction
- Encourages community involvement in shaping the language's future
Cons of swift-evolution
- Less technical in nature, primarily containing textual proposals rather than code
- May be overwhelming for developers looking for specific syntax information
- Updates less frequently than swift-syntax, as language evolution occurs at a slower pace
Code comparison
swift-evolution typically contains proposal documents rather than code. However, it may include code examples to illustrate proposed changes:
// swift-evolution example (hypothetical syntax proposal)
func greet(_ name: String?) {
guard let name else {
print("Hello, stranger!")
return
}
print("Hello, \(name)!")
}
swift-syntax, on the other hand, contains actual Swift code for parsing and manipulating Swift source code:
import SwiftSyntax
let sourceFile = try SyntaxParser.parse(source: "let x = 5")
let variableDecl = sourceFile.statements.first?.item as? VariableDeclSyntax
print(variableDecl?.bindings.first?.pattern)
This comparison highlights the different focuses of the two repositories: swift-evolution for language design and swift-syntax for programmatic manipulation of Swift code.
The Package Manager for the Swift Programming Language
Pros of Swift Package Manager
- More comprehensive functionality for managing dependencies and building Swift projects
- Integrated directly into Xcode, providing a seamless development experience
- Supports a wide range of platforms, including iOS, macOS, tvOS, and watchOS
Cons of Swift Package Manager
- Larger codebase and more complex architecture, potentially making it harder to contribute
- Slower release cycle due to its broader scope and integration with the Swift ecosystem
- May have a steeper learning curve for newcomers compared to Swift Syntax
Code Comparison
Swift Package Manager:
import PackageDescription
let package = Package(
name: "MyPackage",
dependencies: [
.package(url: "https://github.com/example/example-package.git", from: "1.0.0"),
],
targets: [
.target(name: "MyTarget", dependencies: ["ExamplePackage"]),
]
)
Swift Syntax:
import SwiftSyntax
let sourceFile = try SyntaxParser.parse(source: "let x = 5")
let variableName = sourceFile.statements.first?.item.as(VariableDeclSyntax.self)?.bindings.first?.pattern
print(variableName?.description ?? "No variable found")
Language Server Protocol implementation for Swift and C-based languages
Pros of SourceKit-LSP
- Provides a complete Language Server Protocol implementation for Swift
- Offers broader IDE integration capabilities beyond syntax parsing
- Supports advanced features like code completion, refactoring, and diagnostics
Cons of SourceKit-LSP
- More complex setup and configuration compared to Swift Syntax
- Potentially higher resource usage due to its comprehensive feature set
- May have a steeper learning curve for developers new to LSP
Code Comparison
Swift Syntax:
import SwiftSyntax
let sourceFile = try SyntaxParser.parse(source: "let x = 5")
let variableName = sourceFile.statements.first?.item.as(VariableDeclSyntax.self)?.bindings.first?.pattern
SourceKit-LSP:
import SourceKitLSP
let server = SourceKitServer()
server.run()
// LSP requests and responses are handled through JSON-RPC
Summary
Swift Syntax focuses on parsing and manipulating Swift source code, while SourceKit-LSP provides a full-featured language server implementation. Swift Syntax is more lightweight and easier to integrate for specific syntax-related tasks, whereas SourceKit-LSP offers comprehensive IDE support but requires more setup and resources.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Swift Syntax
The swift-syntax package is a set of libraries that work on a source-accurate tree representation of Swift source code, called the SwiftSyntax tree. The SwiftSyntax tree forms the backbone of Swiftâs macro system â the macro expansion nodes are represented as SwiftSyntax nodes and a macro generates a SwiftSyntax tree to be inserted into the source file.
Documentation
You can read SwiftSyntaxâs documentation on swiftpackageindex.com.
A great way to interactively explore the SwiftSyntax tree of a source file is https://swift-ast-explorer.com, developed by @kishikawakatsumi.
A set of example usages of swift-syntax can be found in Examples.
Releases
Releases of SwiftSyntax are aligned with corresponding language and tooling releases, for example the major version 509 of swift-syntax is aligned with Swift 5.9.
To depend on swift-syntax in a SwiftPM package, add the following to your Package.swift
.
dependencies: [
.package(url: "https://github.com/swiftlang/swift-syntax.git", from: "<#latest swift-syntax tag#>"),
],
To add swift-syntax as a dependency of your Xcode project, go to the Package Dependencies tab of your Xcode project, click the plus button and search for https://github.com/swiftlang/swift-syntax.git.
Reporting Issues
If you should hit any issues while using SwiftSyntax, we appreciate bug reports on GitHub Issue.
Contributing
Start contributing to SwiftSyntax see this guide for more information.
Bazel
SwiftSyntax provides an experimental Bazel build configuration, maintained by Keith Smiley.
To use it you can pull the source archive from the relevant release tag
into your WORKSPACE
and depend on the libraries you need from the
BUILD.bazel
file. Each library also has an associated
Library_opt
target (such as SwiftSyntax_opt
) which forces
SwiftSyntax to always build with optimizations enabled. This may help
local runtime performance at the cost of debuggability, and initial
build time. Please tag any issues related to the Bazel configuration with the label "Bazel".
License
Please see LICENSE for more information.
Top Related Projects
The Swift Programming Language
A tool to enforce Swift style and conventions.
This maintains proposals for changes and user-visible enhancements to the Swift Programming Language.
The Package Manager for the Swift Programming Language
Language Server Protocol implementation for Swift and C-based languages
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot