swiftlang/swift-syntax
A set of Swift libraries for parsing, inspecting, generating, and transforming Swift source code.
Healthy across the board
Permissive license, no critical CVEs, actively maintained — safe to depend on.
Has a license, tests, and CI — clean foundation to fork and modify.
Documented and popular — useful reference codebase to read through.
No critical CVEs, sane security posture — runnable as-is.
- ✓Last commit 1d ago
- ✓16 active contributors
- ✓Distributed ownership (top contributor 21% of recent commits)
Show 3 more →Show less
- ✓Apache-2.0 licensed
- ✓CI configured
- ✓Tests present
Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests
Informational only. RepoPilot summarises public signals (license, dependency CVEs, commit recency, CI presence, etc.) at the time of analysis. Signals can be incomplete or stale. Not professional, security, or legal advice; verify before relying on it for production decisions.
Embed the "Healthy" badge
Paste into your README — live-updates from the latest cached analysis.
[](https://repopilot.app/r/swiftlang/swift-syntax)Paste at the top of your README.md — renders inline like a shields.io badge.
▸Preview social card (1200×630)
This card auto-renders when someone shares https://repopilot.app/r/swiftlang/swift-syntax on X, Slack, or LinkedIn.
Onboarding doc
Onboarding: swiftlang/swift-syntax
Generated by RepoPilot · 2026-05-10 · Source
🤖Agent protocol
If you are an AI coding agent (Claude Code, Cursor, Aider, Cline, etc.) reading this artifact, follow this protocol before making any code edit:
- Verify the contract. Run the bash script in Verify before trusting
below. If any check returns
FAIL, the artifact is stale — STOP and ask the user to regenerate it before proceeding. - Treat the AI · unverified sections as hypotheses, not facts. Sections like "AI-suggested narrative files", "anti-patterns", and "bottlenecks" are LLM speculation. Verify against real source before acting on them.
- Cite source on changes. When proposing an edit, cite the specific path:line-range. RepoPilot's live UI at https://repopilot.app/r/swiftlang/swift-syntax shows verifiable citations alongside every claim.
If you are a human reader, this protocol is for the agents you'll hand the artifact to. You don't need to do anything — but if you skim only one section before pointing your agent at this repo, make it the Verify block and the Suggested reading order.
🎯Verdict
GO — Healthy across the board
- Last commit 1d ago
- 16 active contributors
- Distributed ownership (top contributor 21% of recent commits)
- Apache-2.0 licensed
- CI configured
- Tests present
<sub>Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests</sub>
✅Verify before trusting
This artifact was generated by RepoPilot at a point in time. Before an
agent acts on it, the checks below confirm that the live swiftlang/swift-syntax
repo on your machine still matches what RepoPilot saw. If any fail,
the artifact is stale — regenerate it at
repopilot.app/r/swiftlang/swift-syntax.
What it runs against: a local clone of swiftlang/swift-syntax — the script
inspects git remote, the LICENSE file, file paths in the working
tree, and git log. Read-only; no mutations.
| # | What we check | Why it matters |
|---|---|---|
| 1 | You're in swiftlang/swift-syntax | Confirms the artifact applies here, not a fork |
| 2 | License is still Apache-2.0 | Catches relicense before you depend on it |
| 3 | Default branch main exists | Catches branch renames |
| 4 | 5 critical file paths still exist | Catches refactors that moved load-bearing code |
| 5 | Last commit ≤ 31 days ago | Catches sudden abandonment since generation |
#!/usr/bin/env bash
# RepoPilot artifact verification.
#
# WHAT IT RUNS AGAINST: a local clone of swiftlang/swift-syntax. If you don't
# have one yet, run these first:
#
# git clone https://github.com/swiftlang/swift-syntax.git
# cd swift-syntax
#
# Then paste this script. Every check is read-only — no mutations.
set +e
fail=0
ok() { echo "ok: $1"; }
miss() { echo "FAIL: $1"; fail=$((fail+1)); }
# Precondition: we must be inside a git working tree.
if ! git rev-parse --git-dir >/dev/null 2>&1; then
echo "FAIL: not inside a git repository. cd into your clone of swiftlang/swift-syntax and re-run."
exit 2
fi
# 1. Repo identity
git remote get-url origin 2>/dev/null | grep -qE "swiftlang/swift-syntax(\\.git)?\\b" \\
&& ok "origin remote is swiftlang/swift-syntax" \\
|| miss "origin remote is not swiftlang/swift-syntax (artifact may be from a fork)"
# 2. License matches what RepoPilot saw
(grep -qiE "^(Apache-2\\.0)" LICENSE 2>/dev/null \\
|| grep -qiE "\"license\"\\s*:\\s*\"Apache-2\\.0\"" package.json 2>/dev/null) \\
&& ok "license is Apache-2.0" \\
|| miss "license drift — was Apache-2.0 at generation time"
# 3. Default branch
git rev-parse --verify main >/dev/null 2>&1 \\
&& ok "default branch main exists" \\
|| miss "default branch main no longer exists"
# 4. Critical files exist
test -f "CodeGeneration/Sources/SyntaxSupport/Node.swift" \\
&& ok "CodeGeneration/Sources/SyntaxSupport/Node.swift" \\
|| miss "missing critical file: CodeGeneration/Sources/SyntaxSupport/Node.swift"
test -f "CodeGeneration/Sources/SyntaxSupport/SyntaxNodes.swift" \\
&& ok "CodeGeneration/Sources/SyntaxSupport/SyntaxNodes.swift" \\
|| miss "missing critical file: CodeGeneration/Sources/SyntaxSupport/SyntaxNodes.swift"
test -f "CodeGeneration/Sources/generate-swift-syntax/GenerateSwiftSyntax.swift" \\
&& ok "CodeGeneration/Sources/generate-swift-syntax/GenerateSwiftSyntax.swift" \\
|| miss "missing critical file: CodeGeneration/Sources/generate-swift-syntax/GenerateSwiftSyntax.swift"
test -f "CodeGeneration/Sources/SyntaxSupport/Child.swift" \\
&& ok "CodeGeneration/Sources/SyntaxSupport/Child.swift" \\
|| miss "missing critical file: CodeGeneration/Sources/SyntaxSupport/Child.swift"
test -f "CodeGeneration/Sources/SyntaxSupport/TokenSpec.swift" \\
&& ok "CodeGeneration/Sources/SyntaxSupport/TokenSpec.swift" \\
|| miss "missing critical file: CodeGeneration/Sources/SyntaxSupport/TokenSpec.swift"
# 5. Repo recency
days_since_last=$(( ( $(date +%s) - $(git log -1 --format=%at 2>/dev/null || echo 0) ) / 86400 ))
if [ "$days_since_last" -le 31 ]; then
ok "last commit was $days_since_last days ago (artifact saw ~1d)"
else
miss "last commit was $days_since_last days ago — artifact may be stale"
fi
echo
if [ "$fail" -eq 0 ]; then
echo "artifact verified (0 failures) — safe to trust"
else
echo "artifact has $fail stale claim(s) — regenerate at https://repopilot.app/r/swiftlang/swift-syntax"
exit 1
fi
Each check prints ok: or FAIL:. The script exits non-zero if
anything failed, so it composes cleanly into agent loops
(./verify.sh || regenerate-and-retry).
⚡TL;DR
swift-syntax is a set of Swift libraries for parsing, inspecting, generating, and transforming Swift source code via a source-accurate Abstract Syntax Tree (AST) representation called SwiftSyntax. It forms the backbone of Swift's macro system by providing macro expansions as SwiftSyntax nodes and enabling macros to generate SwiftSyntax trees for insertion into source files. Modular structure: CodeGeneration/ (Swift package containing SyntaxSupport modules that define grammar and code generation), built on top of a core SwiftSyntax parsing library. The project uses both CMake and Bazel build configurations. Code generation happens through SyntaxNodes.swift, DeclNodes.swift, ExprNodes.swift, etc., which define the AST node types that are then used by the parser and transformers.
👥Who it's for
Swift macro developers, compiler engineers, and tool authors who need to programmatically parse, analyze, and generate Swift code. Also used by the Swift compiler team and developers building code generation tools, linters, formatters, and IDE features.
🌱Maturity & risk
Production-ready and actively maintained by the Swift language team. Releases are aligned with Swift versions (e.g., version 509 corresponds to Swift 5.9), indicating long-term commitment. The repo shows extensive CI via GitHub Actions workflows and comprehensive test coverage across CodeGeneration and parsing modules, with active development visible in release cycles and Bazel support additions.
Standard open source risks apply.
Active areas of work
Active maintenance aligned with Swift language releases. Recent work includes Bazel support (experimental, version 509.0.0+), CI workflows for auto-merging and publishing releases, and ongoing parser robustness improvements. The repo supports Swift 5.9+ through versioned releases and tracks Swift compiler evolution.
🚀Get running
Clone and build via Swift Package Manager: git clone https://github.com/swiftlang/swift-syntax.git && cd swift-syntax && swift build. For Bazel: add bazel_dep(name = "swift-syntax", version = "600.0.1") to your MODULE.bazel. For Xcode: use the Package Dependencies tab. See Examples/ directory for runnable sample code.
Daily commands:
swift build compiles the core libraries. swift test runs the test suite. For code generation tasks, the CodeGeneration package can be run as a separate Swift package: cd CodeGeneration && swift build.
🗺️Map of the codebase
CodeGeneration/Sources/SyntaxSupport/Node.swift— Defines the core Node abstraction that represents Swift syntax tree elements; foundational for all code generationCodeGeneration/Sources/SyntaxSupport/SyntaxNodes.swift— Aggregates all syntax node definitions (decls, exprs, stmts, patterns, types); the source-of-truth for what nodes exist in the ASTCodeGeneration/Sources/generate-swift-syntax/GenerateSwiftSyntax.swift— Main entry point for code generation; orchestrates template rendering and file output for the entire swiftsyntax libraryCodeGeneration/Sources/SyntaxSupport/Child.swift— Defines how children nodes are specified within parents; critical for understanding node composition and visitor patternsCodeGeneration/Sources/SyntaxSupport/TokenSpec.swift— Defines token kinds and specifications; required for understanding lexical elements in the syntax treeCodeGeneration/Sources/SyntaxSupport/Traits.swift— Defines syntax node traits (e.g., DeclSyntax, ExprSyntax) used for protocol-based type hierarchy and visitor dispatchCodeGeneration/Sources/SyntaxSupport/RawSyntaxNodeKind.swift— Enumerates all raw syntax node kinds; central to node type identification and validation
🛠️How to make changes
Add a new syntax node type
- Define the node in the appropriate category file based on syntax type (decl, expr, stmt, pattern, type, etc.) (
CodeGeneration/Sources/SyntaxSupport/DeclNodes.swift) - Specify children using Child objects with their types, optional flags, and cardinality (
CodeGeneration/Sources/SyntaxSupport/Child.swift) - If creating a new semantic category, add a Trait in Traits.swift to mark nodes of that category (
CodeGeneration/Sources/SyntaxSupport/Traits.swift) - Run the code generator (GenerateSwiftSyntax.swift) to create raw syntax nodes, typed wrappers, visitors, and builders (
CodeGeneration/Sources/generate-swift-syntax/GenerateSwiftSyntax.swift) - Update parser templates if the node needs special parsing logic in swiftparser (
CodeGeneration/Sources/generate-swift-syntax/templates/swiftparser/)
Add a new token kind
- Define the token kind in TokenSpec.swift, specifying keyword text, type (keyword, operator, punctuation), and any metadata (
CodeGeneration/Sources/SyntaxSupport/TokenSpec.swift) - If it's a keyword, also add it to KeywordSpec.swift for reserved word tracking (
CodeGeneration/Sources/SyntaxSupport/KeywordSpec.swift) - Run code generation to produce the TokenKind enum and token factory functions (
CodeGeneration/Sources/generate-swift-syntax/GenerateSwiftSyntax.swift)
Modify or extend the visitor pattern
- Edit Traits.swift to add or modify trait protocols that organize nodes for visitation (
CodeGeneration/Sources/SyntaxSupport/Traits.swift) - Update the visitor template to generate new visit methods for your traits (
CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxVisitorFile.swift) - Run code generation to create updated visitor implementations across all generated node files (
CodeGeneration/Sources/generate-swift-syntax/GenerateSwiftSyntax.swift)
Update builder API for syntactic sugar
- Modify BuildableNodesFile.swift template or add builder-specific logic in SyntaxBuildableNode.swift (
CodeGeneration/Sources/Utils/SyntaxBuildableNode.swift) - If adding result builder support, update ResultBuildersFile.swift template (
CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntaxbuilder/ResultBuildersFile.swift) - Run code generation to render updated builder code (
CodeGeneration/Sources/generate-swift-syntax/GenerateSwiftSyntax.swift)
🔧Why these technologies
- Swift code generation in Swift — Allows compiler developers to define syntax once in Swift and auto-generate all parsing, AST, visitor, and builder code, reducing manual maintenance and ensuring consistency
- Source-accurate tree representation (raw + typed layers) — Raw layer preserves all source information (trivia, exact text positions) while typed layer provides type safety for user code; dual-layer design enables both fidelity and ergonomics
- Visitor & Rewriter patterns — Enables composable, declarative tree traversals and transformations without scattered imperative logic; critical for macros and source transformations
- Builder APIs & result builders — Allows concise, ergonomic construction of syntax trees using Swift's native builder syntax; essential for macro implementations
🪤Traps & gotchas
Version pinning is critical: swift-syntax must match your Swift compiler version (e.g., 509.x for Swift 5.9, 600.x for Swift 6.0). Bazel build requires Bazel toolchain configuration for Swift (non-trivial setup). The CodeGeneration package must be run manually after modifying node definitions—there is no automatic code generation on build. Parser output is not guaranteed stable across patch versions if grammar changes occur. CMake and Bazel builds may diverge; prefer SwiftPM for consistency.
🏗️Architecture
💡Concepts to learn
- Abstract Syntax Tree (AST) — swift-syntax is fundamentally an AST library; understanding tree structure, node types, and traversal is essential to using it effectively
- Source-accurate tree representation — Unlike traditional ASTs that lose formatting, swift-syntax preserves whitespace and comments (trivia) so round-trip source code generation is exact
- Visitor pattern — Macro developers use visitors to traverse SwiftSyntax trees; understanding the visitor pattern enables writing transformations and analyses
- Builder pattern (SwiftSyntaxBuilder) — Macros use builders to construct complex AST trees programmatically; builders ensure well-formed nodes without manual validation
- Trivia (whitespace and comments) — swift-syntax preserves trivia attached to tokens; critical for formatters and tools that must maintain code style
- Grammar-driven code generation — The codebase uses declarative grammar definitions (Trivia.swift, Node.swift) to generate parser code; understanding this meta-level design simplifies modifications
- Swift macro expansion — swift-syntax is the execution engine for Swift macros; macros receive SwiftSyntax trees as input and generate new trees as output
🔗Related repos
apple/swift-evolution— Defines the Swift language specification and grammar that swift-syntax implements; critical for understanding which AST nodes are neededapple/swift-compiler-plugin— Official macro plugin implementation that depends on swift-syntax; shows how macros use the AST tree for code generationswiftlang/swift-argument-parser— Companion library commonly used with swift-syntax for building CLI tools that parse and manipulate Swift codenicklockwood/SwiftFormat— Production code formatter built on swift-syntax; demonstrates large-scale tree traversal and transformation patternsrealm/SwiftLint— Linter built on swift-syntax; shows how to traverse the AST for analysis and issue detection
🪄PR ideas
To work on one of these in Claude Code or Cursor, paste:
Implement the "<title>" PR idea from CLAUDE.md, working through the checklist as the task list.
Add comprehensive parser round-trip tests for experimental features
The CodeGeneration/Sources/SyntaxSupport/ExperimentalFeatures.swift file defines experimental Swift features, but there's no corresponding test suite validating that parsing and unparsing these features produces identical source code (round-trip testing). This is critical for a parser library to ensure fidelity. New contributors can add tests in a new ExperimentalFeaturesRoundTripTests.swift file that programmatically generates test cases for each experimental feature.
- [ ] Review ExperimentalFeatures.swift to identify all defined experimental features
- [ ] Create Tests/SwiftSyntaxTests/ExperimentalFeaturesRoundTripTests.swift with round-trip test cases
- [ ] For each experimental feature, add parse+unparsed assertions ensuring source code fidelity
- [ ] Run tests against the Bazel build system (BUILD.bazel) to integrate into CI
Implement missing parser diagnostic tests for TokenSpec edge cases
TokenSpec.swift in CodeGeneration/Sources/SyntaxSupport defines token specifications, and there's a swiftparserdiagnostics template directory suggesting diagnostic code generation. However, there are likely missing unit tests for edge cases in token parsing and error diagnostics (e.g., malformed tokens, boundary conditions). New contributors can add diagnostic tests that validate proper error messages for malformed Swift syntax.
- [ ] Examine TokenSpec.swift and identify token types without explicit diagnostic coverage
- [ ] Create Tests/SwiftParserDiagnosticsTests/ directory with token-specific diagnostic test cases
- [ ] Add tests for malformed tokens, unclosed delimiters, and invalid syntax combinations
- [ ] Verify tests run in CI via .github/workflows/pull_request.yml
Add integration tests for CodeGeneration targets in Bazel build system
The repo uses both CMake (CMakeLists.txt) and Bazel (BUILD.bazel, .bazelrc) as build systems. The CodeGeneration package generates Swift syntax files, but the Bazel integration for validating generated code consistency is incomplete. New contributors can add Bazel test targets that verify code generation produces consistent, non-divergent output across runs.
- [ ] Review BUILD.bazel and identify missing test targets for CodeGeneration/Sources/generate-swift-syntax
- [ ] Create Bazel build rules that run the code generator and validate output against checked-in generated files
- [ ] Add a Bazel test target (e.g., //CodeGeneration:generated_code_consistency_test) that fails if generated code diverges
- [ ] Update .github/workflows/pull_request.yml to run Bazel code generation validation tests on PRs
🌿Good first issues
- Add documentation examples to SyntaxSupport/*.swift files: most node definitions lack usage examples showing how macros consume them. Pick a common node type (e.g., FunctionDeclSyntax) and add a doc comment with before/after examples.
- Extend TokenSpec.swift and KeywordSpec.swift with validation tests: currently no tests verify that newly defined tokens/keywords integrate correctly into the parser. Create a test file that round-trips token definitions through the parser.
- Fill coverage gaps in Examples/: the Examples/ directory is sparse. Pick a macro use case (e.g., conformance generation, property wrapper expansion) and create a fully worked Example that demonstrates the entire flow from source to SwiftSyntax tree to macro output.
⭐Top contributors
Click to expand
Top contributors
- @PhantomInTheWire — 21 commits
- @rintaro — 16 commits
- @ahoppen — 13 commits
- @dependabot[bot] — 9 commits
- @calda — 9 commits
📝Recent commits
Click to expand
Recent commits
4343379— Change default release version for GitHub action to 605.0.0 + add version marker module (#3325) (rintaro)ac8f50b— Merge pull request #3326 from Padmashree06/Convert-stored-property-to-computed-refactoring (ahoppen)7c0a90b— Remove leading trivia (Padmashree06)0dd94af— [Source Warning Control] Rename '@warn' to '@diagnose' (#3305) (artemcm)f0e6b57— Fixed whitespace error (Padmashree06)3b21f71— Revert "Create pull request template" (shahmishal)a2ed590— Revert "Revise CODEOWNERS for branch management and ownership" (shahmishal)51c8c23— Merge pull request #3316 from swiftlang/shahmishal-patch-1 (shahmishal)d5ee1d6— Add group for swiftlang GitHub Actions (shahmishal)aacb56b— Revise CODEOWNERS for branch management and ownership (shahmishal)
🔒Security observations
The swift-syntax repository demonstrates a generally secure posture for a parsing/syntax library. No critical or high-severity vulnerabilities were identified based on the available file structure and metadata. The codebase follows standard Swift security practices with no obvious injection vectors, hardcoded secrets, or misconfigurations visible. However, a complete security assessment would require: (1) access to full dependency manifests with version pinning details, (2) review of actual source code implementations for logic vulnerabilities, (3) analysis of the GitHub workflows for CI/CD security, and (4) examination of any external data handling in the parser. The low risk profile reflects this being a well-maintained, open-source compiler infrastructure component with standard security controls.
- Low · Missing Package.swift Dependency Details —
Dependencies/Package.swift. The Dependencies/Package.swift file content is not provided in the analysis. Without visibility into the Swift package dependencies and their versions, it's not possible to fully assess whether any transitive dependencies contain known vulnerabilities. This is a limitation of the current analysis scope. Fix: Ensure all dependencies are pinned to specific versions and regularly run 'swift package update' with vulnerability scanning tools like SwiftSec or similar dependency checkers to identify known CVEs. - Low · No secrets detected but configuration files present —
.bazelrc, CMakeLists.txt, .swift-format. While no hardcoded secrets or credentials were found in the provided file structure, configuration files like .bazelrc and CMakeLists.txt are present and should be monitored to prevent accidental credential leakage. Fix: Use pre-commit hooks to scan for secrets. Implement rules in .gitignore to prevent accidental commits of sensitive files. Consider using tools like TruffleHog or git-secrets. - Low · Code generation scripts lack explicit input validation documentation —
CodeGeneration/Sources/generate-swift-syntax/GenerateSwiftSyntax.swift and template files. The codebase contains multiple code generation scripts (GenerateSwiftSyntax.swift, various template files) that process and generate Swift code. While Swift is type-safe, the generation pipeline could benefit from explicit documentation about input validation to prevent malformed syntax tree generation. Fix: Document input validation requirements for all code generation scripts. Add validation assertions for generated syntax trees before output. Consider adding a security-focused code review checklist for generation logic.
LLM-derived; treat as a starting point, not a security audit.
👉Where to read next
- Open issues — current backlog
- Recent PRs — what's actively shipping
- Source on GitHub
Generated by RepoPilot. Verdict based on maintenance signals — see the live page for receipts. Re-run on a new commit to refresh.