関連記事
GitHub - devlights/blog-summary: ブログ「いろいろ備忘録日記」のまとめ
概要
以下、自分用のメモです。
ひょんなことからTree-sitterというライブラリの存在を知りまして、使っててすごく面白かったので自分用にメモ残すことにしました。
公式ドキュメントもしっかり書かれていて素晴らしい。
個人的に実現したかったことが、GoからC言語のソースコードを解析するということだったので、それに関してのメモとなります。
なので、利用するバインディングはGoとなります。
勉強用のリポジトリ
以下に自分用の勉強用リポジトリをアップしています。
Tree-sitterとは?
tree-sitter-docにライブラリの紹介が書いてあります。以下、抜粋です。
Tree-sitter is a parser generator tool and an incremental parsing library. It can build a concrete syntax tree for a source file and efficiently update the syntax tree as the source file is edited. Tree-sitter aims to be:
(Tree-sitterは構文解析ツールであり、インクリメンタル構文解析ライブラリである。ソースファイルの具体的な構文ツリーを構築し、ソースファイルの編集に応じて構文ツリーを効率的に更新することができます。Tree-sitterは次のようなことを目指しています:)
General enough to parse any programming language (あらゆるプログラミング言語を解析できる汎用性)
Fast enough to parse on every keystroke in a text editor (テキストエディタでのすべてのキーストロークを解析するのに十分な速度)
Robust enough to provide useful results even in the presence of syntax errors (構文エラーがあっても有用な結果を提供できるほど頑健である。)
Dependency-free so that the runtime library (which is written in pure C11) can be embedded in any application (依存性がないため、ランタイムライブラリ(純粋なC11で書かれている)をあらゆるアプリケーションに組み込むことができる。)
Go側で利用するライブラリ
Tree-sitterでは、公式バインディングの一つとしてGoがサポートされていますので、以下のライブラリをインストールするだけです。
$ go get github.com/tree-sitter/go-tree-sitter@latest $ go get github.com/tree-sitter/tree-sitter-c/bindings/go@latest
Goのバインディングは、これで完了です。
tree-sitter-cliの用意
Tree-sitterには、専用のCLIツールも用意されています。カスタム定義を作成したり、手軽に構文木がどうなっているのかを確認できたりするので、入れておくと便利。
無くても、ライブラリを用いたTree-sitterが対応している言語の解析はできます。
以下はRustがインストールされている前提の手順です。
$ cargo install tree-sitter-cli
次に、CLIのためにC言語バインディングを配置します。
$ cd $ tree-sitter init-config $ mkdir -p ~/tree-sitter-parsers $ cd ~/tree-sitter-parsers $ git clone https://github.com/tree-sitter/tree-sitter-c.git
~/.config/tree-sitter/config.jsonのparser-directoriesを以下のように設定します。
"parser-directories": [ "/home/xxx/tree-sitter-parsers" ],
これでCLI側で構文木が出力できるようになります。デバッグ時などに便利。
$ tree-sitter parse app.c
参考情報
Goのおすすめ書籍
過去の記事については、以下のページからご参照下さい。
サンプルコードは、以下の場所で公開しています。





