ast-grep
https://gyazo.com/604f6fee55bf9cfa0bcf2076bea35d0d
ASTを解析した上で、grepやlintや置換ができる
grepコマンドの代替としても使えそう
website
github
Rust実装
ast-grepのplayground
examples
ast-grep VSCode
基本
ast-grepのPattern
ast-grepのrule
#WIP
scan周り
いくつかの前提がある
ast-grepは、ast-grepのruleという単位で、1つ1つのクエリを書ける
それらのruleは、yamlに書かれる
ただし、1つのymlに書けるruleは1つだけである
この1つのymlを元にλ ast-grep scanで検索をかけられるが、複数を同時に実行できない
ast-grepは、ruleに対するテストを書ける
ast-grepのruleのtest
ast-grepは、使い回せる汎用的なruleを定義できる
ast-grep: Utility Rule
ast-grepを使うと、上記のように、異なるの役割を持つyamlがたくさん登場する
これらを一箇所で管理するために、特定のdirectoryを設けて
コマンド実行時にそれを参照できるようにしたい
といったことをやるのが
λ ast-grep newとかsgconfig.ymlとか
何ができる #??
linter用?それ以外にも使える?
元々どういうユースケースを想定しているのか知りたい
複数ルールを列挙してその検索を再利用可能にするようなもの?
shellscriptを書いてast-grepを直接呼ぶのとはなにか違うの?
λ ast-grep new
対話形式でsgconfig.ymlを生成する
これは単純に4種類のdirectoryの場所を特定するだけのもの
code:_
my-awesome-project
|- rules # where rules go
|- rule-tests # test cases for rules
|- utils # global utility rules for reusing
|- sgconfig.yml # root configuration file
rule testsってなに?
ast-grepのruleのtest
utility rulesてなに?
globnalなast-grep: Utility Ruleを置く場所
不要であれば無視すれば良い
λ ast-grep new rule
新しいast-grepのruleを作る
https://ast-grep.github.io/guide/scan-project.html#scan-the-code
https://zenn.dev/makotot/articles/ea823805582e5c#スキャン
https://ast-grep.github.io/guide/rule-config.html
rewriteもできる
λ ast-grep scan
tree-sitter
コマンドで1行で書いたり、yamlで書いたりできるらしい
$ sg -p '$A && $A()' -r '$A?.()'
https://gyazo.com/e30d18b7538a9aaa82be96cf5431265c https://ast-grep.github.io/
yamlでの例
ミスってawaitを付けているPromise.allを探す
code:yml
id: no-await-in-promise-all
language: typescript
rule:
pattern: await $A
inside:
pattern: Promise.all($)
stopBy:
not: { any: {kind: array}, {kind: arguments} }
fix: $A
https://ast-grep.github.io/catalog/typescript/#no-await-in-promise-all-array
Structural Search and Replace
https://pleiades.io/help/idea/structural-search-and-replace.html
2023/12/26現在は以下に対応してるっぽい
C
Python
Ruby
Rust
TypeScript
TSX
便利そう
なんでlintいれたんだ