Try Live
Add Docs
Rankings
Pricing
Docs
Install
Theme
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Swift
https://github.com/swiftlang/swift
Admin
Swift is a high-performance, modern, and safe systems programming language developed by Apple,
...
Tokens:
739,191
Snippets:
8,597
Trust Score:
8.8
Update:
2 days ago
Context
Skills
Chat
Benchmark
75.4
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Swift Programming Language Swift is a high-performance system programming language developed by Apple that offers a clean and modern syntax, seamless interoperability with C and Objective-C code, and memory safety by default. Unlike C-derived languages, Swift is a complete and independent language that packages core features like flow control, data structures, and functions alongside high-level constructs including objects, protocols, closures, and generics. Swift embraces modules to eliminate the need for headers and code duplication. This repository contains the source code for the Swift compiler, standard library, runtime, and associated tools. The compiler is built using CMake and Ninja, with the main entry point being the `utils/build-script` automation tool. The repository supports building on macOS, Linux, and Windows, producing both the Swift compiler (`swiftc`) and the complete Swift toolchain. Developers can use this codebase to contribute to Swift itself, build custom toolchains, or understand the compiler's internal architecture. ## Swift Compiler (swiftc) The Swift compiler `swiftc` is the main command-line tool for compiling Swift source code into executables, libraries, or object files. It handles parsing, type-checking, optimization, and code generation through multiple compilation phases. ```bash # Compile a single Swift file to an executable swiftc hello.swift -o hello # Compile with optimization for release swiftc -O main.swift -o main # Compile with size optimization (most production code) swiftc -Osize app.swift -o app # Compile with debug information for development swiftc -Onone -g source.swift -o source # Compile to object file only (no linking) swiftc -c module.swift -o module.o # Compile multiple files into a single executable swiftc file1.swift file2.swift file3.swift -o myapp # Emit Swift module file for library usage swiftc -emit-module -emit-module-path MyLib.swiftmodule MyLib.swift # Compile with whole-module optimization swiftc -whole-module-optimization *.swift -o optimized_app # View all available compiler options swiftc --help swiftc --help-hidden # Hidden/advanced options ``` ## Build Script (utils/build-script) The `build-script` is the primary automation tool for building the Swift toolchain. It configures CMake, invokes Ninja for building, manages caching with Sccache, and runs tests. ```bash # Build the toolchain on macOS with optimizations and debug info utils/build-script --skip-build-benchmarks \ --swift-darwin-supported-archs "$(uname -m)" \ --release-debuginfo --swift-disable-dead-stripping # Build the toolchain on Linux utils/build-script --release-debuginfo # Build with Sccache for faster rebuilds utils/build-script --release-debuginfo --sccache # Build with debug Swift compiler for LLDB debugging utils/build-script --release-debuginfo --debug-swift # Build with debug standard library utils/build-script --release-debuginfo --debug-swift-stdlib # Build and run the test suite utils/build-script --release-debuginfo --test # Build and run validation tests (recommended before large changes) utils/build-script --validation-test # Build with core libraries (Linux) utils/build-script --release-debuginfo --xctest \ --install-libdispatch --install-foundation --install-xctest # Full toolchain build with Swift Package Manager (macOS) utils/build-script --release-debuginfo \ --install-llvm --install-swift --swift-testing-macros --swift-testing \ --install-swift-testing-macros --install-swift-testing -b -p --install-swiftpm \ --swift-driver --install-swift-driver ``` ## Update Checkout (utils/update-checkout) The `update-checkout` script manages all the Git repositories required for building Swift, including LLVM, Clang, SwiftPM, and other dependencies. ```bash # Clone all repositories via SSH (recommended for contributors) git clone git@github.com:swiftlang/swift.git swift cd swift utils/update-checkout --clone-with-ssh # Clone all repositories via HTTPS (read-only) git clone https://github.com/swiftlang/swift.git swift cd swift utils/update-checkout --clone # Update to a specific release branch utils/update-checkout --scheme release/5.10 # Update to a specific tag utils/update-checkout --tag swift-5.10-RELEASE # Show current commit hashes for all repositories utils/update-checkout --dump-hashes ``` ## Ninja Incremental Builds After the initial build, you can use Ninja directly for faster incremental builds when making changes to specific components. ```bash # Set platform variable for cross-platform commands platform=$([[ $(uname) == Darwin ]] && echo macosx || echo linux) # Rebuild only the Swift compiler frontend ninja -C ../build/Ninja-RelWithDebInfoAssert/swift-${platform}-$(uname -m) bin/swift-frontend # Rebuild entire Swift project (compiler + standard library) ninja -C ../build/Ninja-RelWithDebInfoAssert/swift-${platform}-$(uname -m) # Verify the build by checking version ../build/Ninja-RelWithDebInfoAssert/swift-${platform}-$(uname -m)/bin/swift-frontend --version ``` ## Build Toolchain (utils/build-toolchain) The `build-toolchain` script creates distributable Swift toolchain packages, similar to those available on swift.org. ```bash # Build a toolchain with bundle identifier prefix ./swift/utils/build-toolchain com.example # Output: swift-LOCAL-YYYY-MM-DD-a-osx.tar.gz # Build toolchain with dry-run (preview only) ./swift/utils/build-toolchain --dry-run com.mycompany # Build and test the toolchain ./swift/utils/build-toolchain --test com.mycompany # Build with distributed compilation using distcc ./swift/utils/build-toolchain --distcc com.mycompany # Build with sccache for faster subsequent builds ./swift/utils/build-toolchain --sccache com.mycompany # Install toolchain into Xcode (macOS) sudo tar -xzf swift-LOCAL-YYYY-MM-DD-a-osx.tar.gz -C / # Then select via Xcode -> Toolchains ``` ## Testing with lit.py Swift uses LLVM's lit testing framework. Tests can be run using either `utils/run-test` or `lit.py` directly. ```bash # Run all tests using run-test (rebuilds dependencies first) utils/run-test --lit ../llvm-project/llvm/utils/lit/lit.py \ ../build/Ninja-RelWithDebInfoAssert/swift-macosx-$(uname -m)/test-macosx-$(uname -m) # Run tests matching a pattern utils/run-test --lit ../llvm-project/llvm/utils/lit/lit.py \ ../build/Ninja-RelWithDebInfoAssert/swift-macosx-$(uname -m)/test-macosx-$(uname -m) \ --filter="MyTest" # Run tests directly with lit.py (faster, no rebuild) ../llvm-project/llvm/utils/lit/lit.py -sv \ ../build/Ninja-RelWithDebInfoAssert/swift-macosx-$(uname -m)/test-macosx-$(uname -m) # Run specific test directory ../llvm-project/llvm/utils/lit/lit.py -sv \ ../build/Ninja-RelWithDebInfoAssert/swift-macosx-$(uname -m)/test-macosx-$(uname -m)/Parse/ # Run with explicit configuration ../llvm-project/llvm/utils/lit/lit.py -sv \ --param swift_site_config=../build/Ninja-RelWithDebInfoAssert/swift-macosx-$(uname -m)/test-macosx-$(uname -m)/lit.site.cfg \ test/Parse/ # Run tests with timing information ../llvm-project/llvm/utils/lit/lit.py -sv --time-tests test/ # Run tests with timeout (seconds per test) ../llvm-project/llvm/utils/lit/lit.py -sv --timeout=120 test/ # Stop after N failures ../llvm-project/llvm/utils/lit/lit.py -sv --max-failures=5 test/ ``` ## Output File Map (Build System Integration) When integrating Swift into custom build systems, output file maps specify where per-file outputs should be placed. ```json { "/path/to/src/foo.swift": { "object": "/path/to/build/foo.o", "dependencies": "/path/to/build/foo.d", "swift-dependencies": "/path/to/build/foo.swiftdeps", "diagnostics": "/path/to/build/foo.dia" }, "/path/to/src/bar.swift": { "object": "/path/to/build/bar.o", "dependencies": "/path/to/build/bar.d", "swift-dependencies": "/path/to/build/bar.swiftdeps", "diagnostics": "/path/to/build/bar.dia" }, "": { "swift-dependencies": "/path/to/build/main-build-record.swiftdeps" } } ``` ```bash # Use output file map with swiftc swiftc -output-file-map output.json -incremental \ foo.swift bar.swift -emit-executable -o myapp # Compile to object files with incremental builds swiftc -output-file-map output.json -incremental \ -c foo.swift bar.swift # Emit module along with compilation swiftc -output-file-map output.json -incremental \ -emit-module -emit-module-path MyModule.swiftmodule \ foo.swift bar.swift -emit-executable -o myapp ``` ## Compiler Optimization Flags Swift provides various optimization levels and flags for tuning performance and debugging. ```bash # No optimization (development/debugging) swiftc -Onone -g source.swift -o debug_build # Size optimization (recommended for production) swiftc -Osize source.swift -o release_build # Speed optimization (prioritizes performance over size) swiftc -O source.swift -o fast_build # Whole-module optimization (enables cross-file optimizations) swiftc -whole-module-optimization source1.swift source2.swift -o wmo_build # Threaded whole-module (parallel backend compilation) swiftc -whole-module-optimization -num-threads 4 *.swift -o parallel_build # Parallel frontend jobs swiftc -j 4 *.swift -o parallel_frontend # Embed bitcode (for App Store submission) swiftc -embed-bitcode source.swift -o bitcode_build ``` ## Debugging the Compiler When debugging compiler crashes or issues, you can use LLDB with the Swift frontend. ```bash # When compiler crashes, it prints the command - use it with LLDB lldb -- /path/to/swift-frontend -frontend -c -primary-file test.swift \ -emit-module -emit-module-path test.swiftmodule -o test.o # Common LLDB commands for Swift compiler debugging (lldb) breakpoint set -n swift::TypeChecker::typeCheckExpression (lldb) breakpoint set -f Sema.cpp -l 1234 (lldb) run (lldb) bt # backtrace on crash # Print debugging in compiler source code (C++) auto &e = llvm::errs(); e << "Debug: canTypes = ["; llvm::interleaveComma(canTypes, e, [&](auto ty) { ty.dump(e); }); e << "]\n"; # Crash with diagnostic message std::string msg; llvm::raw_string_ostream os(msg); os << "unexpected state: "; value.dump(os); llvm::report_fatal_error(os.str()); ``` ## SDK and Cross-Compilation Swift supports compiling for different platforms using SDK specifications. ```bash # Compile for macOS with SDK xcrun -sdk macosx swiftc MyFile.swift -o myapp # Compile for iOS device xcrun -sdk iphoneos swiftc -target arm64-apple-ios13.0 MyFile.swift -o myapp # Compile for iOS Simulator xcrun -sdk iphonesimulator swiftc -target arm64-apple-ios13.0-simulator MyFile.swift # List available SDKs xcodebuild -showsdks # View target triple options swiftc --help | grep -A5 target ``` ## Standard Library API Categories The Swift standard library is organized into functional groups. Here are the main categories and example usage: ```swift // Collection types let array: [Int] = [1, 2, 3, 4, 5] let dict: [String: Int] = ["a": 1, "b": 2] let set: Set<String> = ["apple", "banana"] // Lazy sequences for performance let lazy = array.lazy.map { $0 * 2 }.filter { $0 > 4 } // String handling with Unicode support let greeting = "Hello, " let name = "Swift" let message = greeting + name let utf8Bytes = message.utf8 // Optional handling let optional: Int? = 42 let unwrapped = optional ?? 0 if let value = optional { print(value) } // Error handling enum MyError: Error { case invalidInput } func process(_ input: String) throws -> Int { guard let result = Int(input) else { throw MyError.invalidInput } return result } // Result type let result: Result<Int, MyError> = .success(42) // Hashing and equality struct Point: Hashable { let x: Int let y: Int } // SIMD vector operations let v1 = SIMD4<Float>(1, 2, 3, 4) let v2 = SIMD4<Float>(5, 6, 7, 8) let sum = v1 + v2 ``` ## Xcode Project Generation Generate an Xcode project for Swift compiler development on macOS. ```bash # Generate Xcode project from Ninja build utils/generate-xcode ../build/Ninja-RelWithDebInfoAssert # This creates Swift.xcodeproj in the parent directory # Open with: open ../Swift.xcodeproj # View additional options utils/generate-xcode --help # After filesystem changes (new files, renames), regenerate: utils/generate-xcode ../build/Ninja-RelWithDebInfoAssert ``` ## Performance Optimization Patterns Swift code patterns that enable better compiler optimizations: ```swift // Use 'final' to enable direct dispatch final class OptimizedClass { var value: Int = 0 func compute() -> Int { return value * 2 } } // Use 'private' for file-scoped optimization private class InternalClass { func process() { /* compiler can inline */ } } // Use ContiguousArray for reference types when NSArray bridging unnecessary let refs: ContiguousArray<MyClass> = [obj1, obj2, obj3] // Use in-place mutation instead of reassignment var items = [1, 2, 3] items.append(4) // Good: in-place // items = items + [4] // Avoid: creates new array // Use value types in arrays for better performance struct Point { var x: Double; var y: Double } let points: [Point] = [...] // Value semantics, better cache locality // Mark class-only protocols for optimization protocol Drawable: AnyObject { func draw() } ``` The Swift compiler repository serves as the foundation for building, testing, and contributing to the Swift programming language. Primary use cases include building custom Swift toolchains for specific platforms, contributing bug fixes and new features to the compiler, implementing new language proposals, and understanding Swift's internal architecture for advanced optimization work. Integration with external build systems follows a pattern of generating output file maps, invoking `swiftc` with appropriate flags for the build configuration, and managing incremental builds through Swift's dependency tracking. For IDE integration, the repository supports generating Xcode projects via `generate-xcode`, CLion configuration through CMake, and general LSP-based editor support through SourceKit-LSP. Contributors typically follow a workflow of cloning via `update-checkout`, building with `build-script`, making changes, running incremental Ninja builds, and testing with lit before submitting pull requests.