Swiftpack.co -  ordazgustavo/swift-tree-sitter as Swift Package
Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
Swift bindings for tree-sitter
.package(url: "https://github.com/ordazgustavo/swift-tree-sitter.git", from: "0.0.3")

Swift TreeSitter

This Package provides Swift bindings to the tree-sitter parsing library.

Basic Usage

First, create a parser:

import SwiftTreeSitter

let parser = Parser()

First, you'll need a Tree-sitter grammar for the language you want to parse. There are many existing grammars .

let javascript = Language(tree_sitter_javascript())
let rust = Language(tree_sitter_rust())
let go = Language(tree_sitter_go())

Then you can assign them to the parser:


Now you can parse source code:

let sourceCode = "let x = 1; console.log(x);"
let tree = parser.parse(source: sourceCode)!
let rootNode = tree.rootNode

XCTAssertEqual(rootNode.kind, "program")
XCTAssertEqual(rootNode.startPosition.column, 0)
XCTAssertEqual(rootNode.endPosition.column, 26)


Once you have a syntax tree, you can update it when your source code changes. Passing in the previous edited tree makes parse run much more quickly:

// Replace 'let' with 'const'
let newSourceCode = "const x = 1; console.log(x);"

  startByte: 0,
  oldEndByte: 3,
  newEndByte: 5,
  startPosition: Point(row: 0, column: 0),
  oldEndPosition: Point(row: 0, column: 3),
  newEndPosition: Point(row: 0, column: 5)

let newTree = parser.parse(source: newSourceCode, oldTree: tree)

Text Input

The source code to parse can be provided either either as a string, a slice, a vector, or as a function that returns a slice.

let lines = source.components(separatedBy: .newlines)

let tree = parser.parseWith { (offset, position) -> Substring.UTF8View in
  let row = Int(position.row)
  let col = Int(position.column)
  if row < lines.count {
    let line = lines[row].utf8
    if col < line.count {
      return line[line.index(line.startIndex, offsetBy: col)...]
    } else {
      return Substring("\n").utf8
  } else {
    return Substring().utf8


⚠️ Please note that this is still a work in progress, PRs welcome!


This package is available through Swift Package Manager

.package(url: "https://github.com/ordazgustavo/swift-tree-sitter", from: "0.0.3")


Stars: 5
Last commit: 6 weeks ago

Ad: Job Offers

iOS Software Engineer @ Perry Street Software
Perry Street Software is Jack’d and SCRUFF. We are two of the world’s largest gay, bi, trans and queer social dating apps on iOS and Android. Our brands reach more than 20 million members worldwide so members can connect, meet and express themselves on a platform that prioritizes privacy and security. We invest heavily into SwiftUI and using Swift Packages to modularize the codebase.

Release Notes

42 weeks ago

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API