GritQL
https://gyazo.com/58131267ce1bbecef59c3df21e33abc7
検索・置換・修正を行うための宣言的なクエリ言語
GPT-4.icon
AST(抽象構文木)を直接操作せずに、自然なコードに近い形でパターンマッチと書き換えができます。
🌱 基本の考え方
🔍 クエリは「コード片」
$ grit apply 'console.log($_)'
これは「すべての console.log(...) を検索せよ」という意味。$_ は任意の値を表す メタ変数(プレースホルダ)です。
🔁 置換も自然に書ける
$ grit apply 'console.log($msg) => winston.log($msg)'
これは「console.log(...) を winston.log(...) に置き換えよ」という命令。
🧠 GritQLの強み
✅ 宣言的で読みやすい
ASTやトラバース処理を知らなくても「見たままのコード」で書ける。
🚀 パフォーマンス重視
Rust製で非常に高速。10M+行のコードでも実行できるよう最適化されています。
🧩 再利用可能なモジュール
Gritには標準で 200+ の共通パターンが含まれており、それらを再利用したり、自分で定義して共有できます。
🔧 実用例
grit.yaml にパターン定義
code:yaml
# .grit/grit.yaml
patterns:
- name: use_winston
level: error
body: |
console.log($msg) => winston.log($msg) where {
$msg <: not within or {
it($_, $_), test($_, $_), describe($_, $_)
}
}
このパターンは、「console.log(...) を winston.log(...) に書き換える。ただし test, it, describe 内部は除外する」ことを意味しています。
syntax highlightが効くなら良さそうmrsekut.icon
コマンドで適用:
$ grit apply use_winston
🔎 Lintとして利用
check コマンドで、コードがパターンに準拠しているかどうかをチェックできます。eslint のようなカスタムLintになります。
🎓 高度な例
try-catch外のconsole.logを削除
code:gritql
console.log($log) => . where {
$log <: not within try { $_ } catch { $_ }
}
特定クラスのメソッド呼び出しを書き換え
code:gritql
$instance.oldMethod($args) => $instance.newMethod($args) where {
$program <: contains $instance = new TargetClass($_)
}