ast-grepのPattern
from ast-grep
#wip
ast-grepのPattern
ASTに一致する
https://ast-grep.github.io/guide/quick-start.html#pattern
メタ変数
e.g. $METAVAR
$と大文字のやつ
https://ast-grep.github.io/guide/pattern-syntax.html#meta-variable
これって全部予約語なん #??
ちがう
正規表現の.に対して変数を設定できるイメージ
1つのメタ変数は1つのASTにマッチする
そもそもどういうものがASTのノードになるのかということを知らないといけない
それで言うと、tsにおける型とかがASTとしてどう扱われているかあんまり知らないmrsekut.icon
const a = await f<string>(args)みたいな式がどういうASTになるのか
特に型周り
$$$
マルチメタ変数
0個以上のASTノードにマッチする
https://ast-grep.github.io/guide/pattern-syntax.html#multi-meta-variable
code:console.log($$$)の例
console.log() // matches zero AST node
console.log('hello world') // matches one node
console.log('debug: ', key, value) // matches multiple nodes
console.log(...args) // it also matches spread
function $FUNC($$$ARGS) { $$$ }
任意の関数定義にマッチ
もちろん$FUNCは$Fでもいいし、$$$ARGSは$$$でもいい
変数名は自分でつける
例 console.log($GREETING)
以下に一致する
code:js
function tryAstGrep() {
console.log('Hello World')
}
const multiLineExpression =
console
.log('Also matched!')
以下は一致しない
code:js
// console.log(123) in comment is not matched
'console.log(123) in string' // is not matched as well
console.log() // mismatch argument
console.log(a, b) // too many arguments
https://ast-grep.github.io/guide/pattern-syntax.html
パターンの書き方が合っているかは、playgroundで試してみると良い
Non Capturing Match
https://ast-grep.github.io/guide/pattern-syntax.html#non-capturing-match
$_Aみたいに_で始まるやつ
マッチしないさせない
Unnamed Nodes
https://ast-grep.github.io/guide/pattern-syntax.html#capture-unnamed-nodes
Unnamed Nodesを含めてマッチさせる
デフォルトだとマッチしない
$2つで始める
e.g. $$A
https://zenn.dev/makotot/articles/ea823805582e5c#匿名ノード
よくわからん
いやむずいな!mrsekut.icon
f($$$)やf<$$$>($$$)で
f<string>(hoge)がマッチしない
f<$T>($$$)こうかかないといけないのか
AIのサポートが欲しいよ〜〜〜〜〜
こうやって呼んでいる関数
code:ts
const a = await f<unknown>(b)
f<$T>($A)だとマッチしない
await f<$T>($A)のようにawaitも含める必要がある
ast-grerpと関係ないけどASTのイメージを掴む必要がある
適当にぐるとこれを見つけた
TypeScript AST Viewer
https://ts-ast-viewer.com/#code/MYewdgzgLgBAhjAvPA7nAlrAZgHgN4QBcM0ATumAOYC+AfABQBGAlEA
いやこれはast-grepのplaygroundを使って、左下の枠とか見ろってことっぽい
でもそもそも正規表現の難度を考えれば妥当ではあるか
https://ast-grep.github.io/catalog/typescript/