はじめに
七尾百合子さん、お誕生日 76日目 おめでとうございます! nikkieです。
ast-grep が使っている tree-sitter について環境構築しました
目次
- はじめに
- 目次
- tree-sitterを完全に理解したい
- macOSにインストール
- Pythonコードをパースできるようにする
- tree-sitterでPythonコードをパース
- tree-sitter ecosystem
- 終わりに
tree-sitterを完全に理解したい
flake8-kotoha を ast-grep でも実現できるのではと手を動かしました。
やりたいことはできたのですが、ast-grep & tree-sitter と新しいツールが2つも登場し、非常にハマりました。
小さな理解を積み上げるべく、まずは tree-sitter を触ります。
o3 + Web search で見つけた我が師 simonw さんの記事からリンクを辿っていきました。
Using tree-sitter with Python | Simon Willison’s TILs
Two useful posts by Douglas Creager: Getting started with tree-sitter and A map of the tree-sitter ecosystem.
macOSにインストール
% sw_vers ProductName: macOS ProductVersion: 14.5 BuildVersion: 23F79
「Installing tree-sitter」を参考に、brewでインストールしました。
https://formulae.brew.sh/formula/tree-sitter
% tree-sitter --version tree-sitter 0.25.5
コマンド自体は生えるのですが、もう少し設定が必要です
Pythonコードをパースできるようにする
上記のブログを引き続き参考にします。
「Installing a grammar」より
※以下の$HOMEは、ご自身の環境の値で展開の上で参照ください
tree-sitter init-config$HOME/.config/tree-sitter/config.jsonを生成- ref: https://tree-sitter.github.io/tree-sitter/cli/init-config.html
- tree-sitter/tree-sitter-pythonをクローン
- どこでもいい認識ですが、
$HOME/.config/tree-sitter/src/にしました
- どこでもいい認識ですが、
- 1で作った
config.jsonを編集
これでPythonの文法(Grammar)がインストールされました!
tree-sitterでPythonコードをパース
tree-sitter parseコマンドにPythonファイルのパスを渡します。
# examples/use_iterable.py def plus_one_ng(numbers: list[int]) -> list[int]: return [n + 1 for n in numbers]
% tree-sitter parse examples/use_iterable.py
(module [0, 0] - [2, 0]
(function_definition [0, 0] - [1, 35]
name: (identifier [0, 4] - [0, 15])
parameters: (parameters [0, 15] - [0, 35]
(typed_parameter [0, 16] - [0, 34]
(identifier [0, 16] - [0, 23])
type: (type [0, 25] - [0, 34]
(generic_type [0, 25] - [0, 34]
(identifier [0, 25] - [0, 29])
(type_parameter [0, 29] - [0, 34]
(type [0, 30] - [0, 33]
(identifier [0, 30] - [0, 33])))))))
return_type: (type [0, 39] - [0, 48]
(generic_type [0, 39] - [0, 48]
(identifier [0, 39] - [0, 43])
(type_parameter [0, 43] - [0, 48]
(type [0, 44] - [0, 47]
(identifier [0, 44] - [0, 47])))))
body: (block [1, 4] - [1, 35]
(return_statement [1, 4] - [1, 35]
(list_comprehension [1, 11] - [1, 35]
body: (binary_operator [1, 12] - [1, 17]
left: (identifier [1, 12] - [1, 13])
right: (integer [1, 16] - [1, 17]))
(for_in_clause [1, 18] - [1, 34]
left: (identifier [1, 22] - [1, 23])
right: (identifier [1, 27] - [1, 34])))))))
ast-grepのplayground(左下)で見たやつだ〜!
tree-sitter ecosystem
- 上でダウンロードした tree-sitter-python は「Language parsers」
tree-sitter-$LANGUAGEという名前のリポジトリ
- tree-sitter の言語バインディングも存在
- tier 1のRustとWASMバインディングはtree-sitter/tree-sitterに含まれる
- Pythonはtier 2なので別リポジトリ(tree-sitter/py-tree-sitter)
終わりに
macOSで tree-sitter の環境構築をし、Pythonコードをパースできました🎄
tree-sitterはHomebrew(など)でインストールできます。
プログラミング言語ごとの文法も合わせてインストールする必要があります:
- init-config
- 文法のリポジトリをclone
- configのparser-directoriesに記載
tree-sitter では構文木のクエリもサポートしています。
Queries - Tree-sitter
完全理解に向けて、残すはクエリかなと思います