tree: 828d1567f502a335afcb10d3d20cc3d20dedb08f [path history] [tgz]
  1. AtomicCache.swift
  2. CMakeLists.txt
  3. Diagnostic.swift
  4. DiagnosticConsumer.swift
  5. DiagnosticEngine.swift
  6. JSONDiagnosticConsumer.swift
  7. PrintingDiagnosticConsumer.swift
  8. RawSyntax.swift
  9. README.md
  10. SourcePresence.swift
  11. SwiftcInvocation.swift
  12. SwiftSyntax.swift
  13. Syntax.swift
  14. SyntaxBuilders.swift.gyb
  15. SyntaxChildren.swift
  16. SyntaxCollections.swift.gyb
  17. SyntaxData.swift
  18. SyntaxFactory.swift.gyb
  19. SyntaxKind.swift.gyb
  20. SyntaxNodes.swift.gyb
  21. SyntaxRewriter.swift.gyb
  22. TokenKind.swift.gyb
  23. Trivia.swift.gyb
tools/SwiftSyntax/README.md

SwiftSyntax

SwiftSyntax is a set of Swift bindings for the libSyntax library. It allows for Swift tools to parse, inspect, generate, and transform Swift source code.

Note: SwiftSyntax is still in development, and the API is not guaranteed to be stable. It's subject to change without warning.

Usage

First, install the latest Swift master toolchain from swift.org. This will ensure you have the latest version of SwiftSyntax, which is necessary as SwiftSyntax evolves. Next, select that toolchain in Xcode, using the File>Toolchains menu.

Then, open a new Swift file or create a new Swift package and import SwiftSyntax. From there, you'll be able to use the SwiftSyntax API.

Example

This is a program that adds 1 to every integer literal in a Swift file.

import SwiftSyntax
import Foundation

/// AddOneToIntegerLiterals will visit each token in the Syntax tree, and
/// (if it is an integer literal token) add 1 to the integer and return the
/// new integer literal token.
class AddOneToIntegerLiterals: SyntaxRewriter {
  override func visit(_ token: TokenSyntax) -> Syntax {
    // Only transform integer literals.
    guard case .integerLiteral(let text) = token.tokenKind else {
      return token
    }

    // Remove underscores from the original text.
    let integerText = String(text.filter { ("0"..."9").contains($0) })

    // Parse out the integer.
    let int = Int(integerText)!

    // Return a new integer literal token with `int + 1` as its text.
    return token.withKind(.integerLiteral("\(int + 1)"))
  }
}

let file = CommandLine.arguments[1]
let url = URL(fileURLWithPath: file)
let sourceFile = try SourceFileSyntax.parse(url)
let incremented = AddOneToIntegerLiterals().visit(sourceFile)
print(incremented)

This example turns this:

let x = 2
let y = 3_000

into:

let x = 3
let y = 3001