Swift grammar for tree-sitter
Actively maintained. Last release 8 weeks ago, commits in 18 of the last 26 weeks. A safe choice.
pip install tree-sitter-swifttree-sitter-swift
This contains a tree-sitter grammar for the Swift programming language.
Getting started
To use this parser to parse Swift code, you'll want to depend on either the Rust crate or the NPM package.
Rust
To use the Rust crate, you'll add this to your Cargo.toml:
tree-sitter = "0.23.0"
tree-sitter-swift = "=0.7.4"
Then you can use a tree-sitter parser with the language declared here:
let mut parser = tree_sitter::Parser::new();
parser.set_language(tree_sitter_swift::language())?;
// ...
let tree = parser.parse(&my_source_code, None)
.ok_or_else(|| /* error handling code */)?;
Javascript
To use this from NPM, you'll add similar dependencies to package.json:
"dependencies: {
"tree-sitter-swift": "0.7.4",
"tree-sitter": "^0.22.1"
}
Your usage of the parser will look like:
const Parser = require("tree-sitter");
const Swift = require("tree-sitter-swift");
const parser = new Parser();
parser.setLanguage(Swift);
// ...
const tree = parser.parse(mySourceCode);
Editing the grammar
With this package checked out, a common workflow for editing the grammar will look something like:
- Make a change to
grammar.ts. - Run
npm install && npm testto see whether the change has had impact on existing parsing behavior. The defaultnpm testtarget requiresvalgrindto be installed; if you do not have it installed, and do not wish to, you can substitutetree-sitter testdirectly. - Run on some real Swift codebase and see whether (or where) it fails.