いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

Goメモ-598 (Tree-sitterメモ-02)(パーサーの生成と言語の設定)

関連記事

GitHub - devlights/blog-summary: ブログ「いろいろ備忘録日記」のまとめ

概要

以下、自分用のメモです。前回までのメモは関連記事にかかれている ブログ記事まとめ よりどうぞ。

今回は、パーサーの生成と言語の設定について。

以下、Using Parsersから引用。

Tree-sitter's parsing functionality is implemented through its C API, with all functions documented in the tree_sitter/api.h header file, but if you're working in another language, you can use one of the following bindings found here, each providing idiomatic access to Tree-sitter's functionality. Of these bindings, the official ones have their own API docs hosted online at the following pages:

(Tree-sitterのパース機能はC APIで実装されており、すべての関数はtree_sitter/api.hヘッダファイルに記述されていますが、他の言語で作業している場合は、Tree-sitterの機能への慣用的なアクセスを提供する以下のバインディングのいずれかを使用することができます。これらのバインディングのうち、公式のものは以下のページに独自のAPIドキュメントがあります:)

公式バインディングには以下が存在します。(2025-07 現在)

  • C#
  • Go
  • Haskell
  • Java (JDK 22+)
  • JavaScript (Node.js)
  • JavaScript (Wasm)
  • Kotlin
  • Python
  • Rust
  • Swift
  • Zig

どのバインディングを利用していても、使い方は大差ないため一つ覚えれば他の言語バインディングでも通用します。

手順としては

1.parserの生成(NewParser)

2.言語の設定(SetLanguage)

となります。

サンプル

main.go

package main

import (
    "log"

    tree_sitter "github.com/tree-sitter/go-tree-sitter"
    tree_sitter_c "github.com/tree-sitter/tree-sitter-c/bindings/go"
)

func main() {
    if err := run(); err != nil {
        log.Fatal(err)
    }
}

func run() error {
    //
    // 最初の手順は
    //   1. パーサーを生成
    //   2. 言語を設定
    // となる。
    //
    // パーサーはCloseする必要がある。
    //
    var (
        p   *tree_sitter.Parser   = tree_sitter.NewParser()
        l   *tree_sitter.Language = tree_sitter.NewLanguage(tree_sitter_c.Language())
        err error
    )
    defer p.Close()

    if err = p.SetLanguage(l); err != nil {
        return err
    }

    return nil
}

参考情報

tree-sitter.github.io

github.com

Goのおすすめ書籍


過去の記事については、以下のページからご参照下さい。

サンプルコードは、以下の場所で公開しています。