| disable-model-invocation | true |
| name | tree-sitter |
| description | AST parsing, S-expression queries, tag extraction via tree-sitter CLI. Use when parsing code into AST, extracting tags, visualizing syntax trees, or performing structural analysis beyond ast-grep. |
tree-sitter CLI
tree-sitter CLI๋ก AST ๋คํ, S-expression ์ฟผ๋ฆฌ, ํ๊ทธ ์ถ์ถ์ ์ํํฉ๋๋ค.
ํต์ฌ ์ฒ ํ:
- ast-grep ์ฐ์ : ๊ฒ์/๋์ฒด๋ ast-grep, tree-sitter๋ ๋ถ์/์ดํด ๋ชฉ์
- AST ์๊ฐํ: ์ฝ๋ ๊ตฌ์กฐ๋ฅผ ํธ๋ฆฌ๋ก ํ์ธํ์ฌ ์ ํํ ๋
ธ๋ ํ์
ํ์
- S-expression ์ฟผ๋ฆฌ: predicates๋ก ์ ๋ฐํ ๊ตฌ์กฐ์ ๊ฒ์ (neovim query์ ๋์ผ ๋ฌธ๋ฒ)
- ํ๊ทธ ์ถ์ถ: ์ ์/์ฐธ์กฐ๋ฅผ ๊ตฌ์กฐ์ ์ผ๋ก ์ถ์ถ (ctags ๋์ฒด)
Prerequisites
tree-sitter dump-languages
"not configured" ๊ฒฝ๊ณ ์ โ ์ํฌํ๋ก์ฐ 1 ์คํ.
Instructions
์ํฌํ๋ก์ฐ 1: Setup (on-demand ํ์ ์ค์น)
dump-languages ์ถ๋ ฅ์ ์ธ์ด๊ฐ ์์ผ๋ฉด grammar์ ์ค์นํ๋ค.
tree-sitter init-config
cd ~/.local/share/tree-sitter/grammars
git clone --depth 1 https://github.com/tree-sitter/tree-sitter-<์ธ์ด>
์ํฌํ๋ก์ฐ 2: Parse (AST ๋คํ)
์ฟผ๋ฆฌ ์์ฑ ์ ๋
ธ๋ ํ์
ํ์
์ ํ์.
tree-sitter parse --no-ranges file.py
tree-sitter parse --cst file.py
tree-sitter parse --xml file.py
tree-sitter parse --scope source.python file.txt
์ถ๋ ฅ ์์:
(function_definition
name: (identifier)
parameters: (parameters (identifier) (identifier))
body: (block (return_statement)))
๋
ธ๋ ํ์
(function_definition)๊ณผ ํ๋๋ช
(name:, body:)์ ํ์ธํ์ฌ query ํจํด ์์ฑ์ ์ฌ์ฉ.
์ํฌํ๋ก์ฐ 3: Query (S-expression ์ฟผ๋ฆฌ)
S-expression ํจํด์ผ๋ก ์ฝ๋๋ฅผ ๊ฒ์ํ๋ค. .scm ํ์ผ์ ์์ฑ ํ ์คํ.
;; queries/find-functions.scm
(function_definition
name: (identifier) @func.name)
tree-sitter query queries/find-functions.scm file.py
tree-sitter query queries/find-functions.scm src/
tree-sitter query --captures queries/q.scm file.py
tree-sitter query --row-range 10-50 queries/q.scm file.py
S-expression ์ฟผ๋ฆฌ ๋ฌธ๋ฒ์ resources/01-query-syntax.md ์ฐธ์กฐ.
์ํฌํ๋ก์ฐ 4: Tags (ํ๊ทธ ์ถ์ถ)
์ฝ๋์์ ์ ์(definition)์ ์ฐธ์กฐ(reference)๋ฅผ ์ถ์ถํ๋ค.
tree-sitter tags file.py
tree-sitter tags src/
์ค์ ์์น
- Parse ๋จผ์ : ์ฟผ๋ฆฌ ์์ฑ ์ ๋ฐ๋์
parse๋ก ๋
ธ๋ ํ์
ํ์ธ
- ์ฟผ๋ฆฌ ํ์ผ ์ฌ์ฉ:
.scm ํ์ผ ์์ฑ (์ฌ์ฌ์ฉ, ๊ฐ๋
์ฑ)
- ์ธ์ด๋ณ ๋
ธ๋ ์ฐจ์ด: ๊ฐ์ ๊ฐ๋
์ด๋ผ๋ ์ธ์ด๋ง๋ค ๋
ธ๋ ํ์
์ด ๋ค๋ฆ
Examples
AST ๊ตฌ์กฐ ํ์
User: "์ด Python ํ์ผ์ AST ๊ตฌ์กฐ ๋ณด์ฌ์ค"
โ tree-sitter parse --no-ranges file.py โ ๋
ธ๋ ํ์
๊ณผ ํ๋ ๊ตฌ์กฐ ๋ณด๊ณ
๋ณต์กํ ์ฟผ๋ฆฌ
User: "๋ฐ์ฝ๋ ์ดํฐ๊ฐ ๋ถ์ async ํจ์๋ง ์ฐพ์์ค"
โ parse๋ก ๋
ธ๋ ํ์
ํ์ธ โ .scm ์ฟผ๋ฆฌ ์์ฑ โ tree-sitter query query.scm src/
References