Swiftpack.co - Package - yanagiba/swift-ast

Swift Abstract Syntax Tree

swift-ast master swift-lint master swift-transform pending

Travis CI Status codecov Swift 5.1 Swift Package Manager Platforms License

Swift Abstract Syntax Tree is an initiative to parse Swift Programming Language in Swift itself. The output of this utility is the corresponding Abstract Syntax Tree (AST) of the source code.

The AST produced in this tool is intended to be consumed in various scenarios. For example, source-to-source transformations like swift-transform and linting tools like swift-lint.

Refactoring, code manipulation and optimization can leverage this AST as well.

Other ideas could be llvm-codegen or jvm-codegen (thinking about JSwift) that consumes the AST and converts them into binary or bytecode. I have some proof-of-concepts, llswift-poc and jswift-poc, respectively. If you are interested in working on the codegens, send me email ryuichi@yanagiba.org.

Swift Abstract Syntax Tree is part of Yanagiba Project. Yanagiba umbrella project is a toolchain of compiler modules, libraries, and utilities, written in Swift and for Swift.

A Work In Progress

The Swift Abstract Syntax Tree is still in active development. Though many features are implemented, some with limitations.

Pull requests for new features, issues and comments for existing implementations are welcomed.

Please also be advised that the Swift language is under rapid development, its syntax is not stable. So the details are subject to change in order to catch up as Swift evolves.



Standalone Tool

To use it as a standalone tool, clone this repository to your local machine by

git clone https://github.com/yanagiba/swift-ast

Go to the repository folder, run the following command:

swift build -c release

This will generate a swift-ast executable inside .build/release folder.

Adding to swift Path (Optional)

It is possible to copy the swift-ast to the bin folder of your local Swift installation.

For example, if which swift outputs


Then you can copy swift-ast to it by

cp .build/release/swift-ast /Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift-ast

Once you have done this, you can invoke swift-ast by calling swift ast in your terminal directly.

Embed Into Your Project

Add the swift-ast dependency to Package.swift:

// swift-tools-version:5.0

import PackageDescription

let package = Package(
  name: "MyPackage",
  dependencies: [
    .package(url: "https://github.com/yanagiba/swift-ast.git", from: "0.19.9")
  targets: [
    .target(name: "MyTarget", dependencies: ["SwiftAST+Tooling"]),
  swiftLanguageVersions: [.v5]


Command Line

Simply append the path of the file to swift-ast. It will dump the AST to the console.

swift-ast path/to/Awesome.swift

Multiple files can be parsed with one call:

swift-ast path1/to1/foo.swift path2/to2/bar.swift ... path3/to3/main.swift

CLI Options

By default, the AST output is in a plain text format without indentation nor color highlight to the keywords. The output format can be changed by providing the following option:

  • -print-ast: with indentation and color highlight
  • -dump-ast: in a tree structure
  • -diagnostics-only: no output other than the diagnostics information

In addition, -github-issue can be provided as the first argument option, and the program will try to generate a GitHub issue template with pre-filled content for you.

Use AST in Your Code

Loop Through AST Nodes

import AST
import Parser
import Source

do {
  let sourceFile = try SourceReader.read(at: filePath)
  let parser = Parser(source: sourceFile)
  let topLevelDecl = try parser.parse()

  for stmt in topLevelDecl.statements {
    // consume statement
} catch {
  // handle errors

Traverse AST Nodes

We provide a pre-order depth-first traversal implementation on all AST nodes. In order to use this, simply write your visitor by conforming ASTVisitor protocol with the visit methods for the AST nodes that are interested to you. You can also write your own traversal implementations to override the default behaviors.

Returning false from traverse and visit methods will stop the traverse.

class MyVisitor : ASTVisitor {
  func visit(_ ifStmt: IfStatement) throws -> Bool {
    // visit this if statement

    return true
let myVisitor = MyVisitor()
let topLevelDecl = MyParse.parse()


Build & Run

Building the entire project can be done by simply calling:


This is equivalent to

swift build

The dev version of the tool can be invoked by:

.build/debug/swift-ast path/to/file.swift

Running Tests

Compile and run the entire tests by:

make test


Ryuichi Sai

  • http://github.com/ryuichis
  • ryuichi@yanagiba.org


Swift Abstract Syntax Tree is available under the Apache License 2.0. See the LICENSE file for more info.


Stars: 241


Used By

Total: 0


0.4.2 - 2018-04-01 00:21:56

  • Newline escape in new lines
  • Support Postfixes in KeypathExpression
  • Lex long decimals
  • Parsing additional Swift 4 features
  • Allow dollar signed used as identifier body
  • Introduce Identifier as a replacement of plain string
  • Swift 4.1 migration
  • Bug fixes
  • code refactoring

0.4.1 - 2017-08-20 16:41:29

  • Catch up with Bocho 0.1.0 release

0.4.0 - 2017-08-14 17:07:26

  • Introduce libTooling
  • Assign lexical parent
  • Introduce sequence expression, and when enabled, fold it with hardcoded operator precedences
  • Support shebang
  • Other minor changes

0.3.5 - 2017-06-22 17:01:04

  • Force label name has to be on the same line as break or continue statement
  • swift-lint 0.1.3 integration and minor refactorings

0.3.4 - 2017-06-16 01:28:14

  • The source code comments are now exposed through TopLevelDeclaration

0.3.3 - 2017-06-15 19:39:48

  • Fix raw-value typed enum declaration by supporting boolean literals

0.3.2 - 2017-06-15 17:32:15

  • Extended OptionalPattern

0.3.1 - 2017-06-11 16:23:32

  • Updated to Swift 4 package manager description

0.3.0 - 2017-06-11 02:41:05

  • Parse Swift 4 new language features
  • Leverage Swift 4 feature to improve code quality of this repo

0.2.0 - 2017-05-23 13:10:37

  • Dump AST to terminal
  • Print AST to terminal
  • Enhancements to diagnostic messages
  • Improvements to test coverage
  • Github issue generation
  • Assign values for #file, #line, and #column
  • Remove deprecated dynamic-type expression

0.1.4 - 2017-04-25 03:08:12

  • Parse Swift 3.1
  • ASTVisitor with default traversal implementation

0.1.3 - 2015-12-31 09:34:24

  • ASTContext contains the original source file

0.1.2 - 2015-12-26 08:45:39

  • Assign source code range to token
  • Assign source code range to AST nodes
  • Minor improvements to ImportDeclaration
    • Introduce ImportKind
    • Additional error handling
    • Code quality enhancements

0.1.1 - 2015-12-25 04:09:27

Initial release with tokenizing source code and parsing import declaration.

Releasing in order to be kicked up by SPM.