Skip to content

Instantly share code, notes, and snippets.

@mizchi
Last active June 11, 2025 03:39
Show Gist options
  • Save mizchi/1b12a367ac52cfa2f193c4152161254d to your computer and use it in GitHub Desktop.
Save mizchi/1b12a367ac52cfa2f193c4152161254d to your computer and use it in GitHub Desktop.
# ast-grep 使用例チートシート
# ==========================================
# 基本的なパターンマッチング
# ==========================================
# 1. 関数呼び出しの検索
# CLI: ast-grep -p 'console.log($MSG)' src/
id: find-console-log
language: JavaScript
rule:
pattern: console.log($MSG)
---
# 2. 関数定義の検索(各種パターン)
# CLI: ast-grep -p 'function $NAME($$) { $$ }' src/
id: find-function-definitions
language: JavaScript
rule:
any:
# 通常の関数定義
- pattern: function $NAME($$PARAMS) { $$BODY }
# アロー関数(ブロック形式)
- pattern: const $NAME = ($$PARAMS) => { $$BODY }
# アロー関数(式形式)
- pattern: const $NAME = ($$PARAMS) => $EXPR
# オブジェクトメソッド
- pattern: $NAME($$PARAMS) { $$BODY }
# クラスメソッド
- pattern: |
class $CLASS {
$NAME($$PARAMS) { $$BODY }
}
# 非同期関数
- pattern: async function $NAME($$PARAMS) { $$BODY }
- pattern: const $NAME = async ($$PARAMS) => { $$BODY }
---
# 3. exportされたシンボルの検索
# CLI: ast-grep -p 'export $SYMBOL' src/
id: find-exported-symbols
language: JavaScript
rule:
any:
# 名前付きexport
- pattern: export { $$SYMBOLS }
# デフォルトexport(関数)
- pattern: export default function $NAME($$) { $$ }
# デフォルトexport(変数)
- pattern: export default $VALUE
# 宣言と同時にexport
- pattern: export const $NAME = $VALUE
- pattern: export function $NAME($$) { $$ }
- pattern: export class $NAME { $$ }
# 再export
- pattern: export { $$SYMBOLS } from $MODULE
- pattern: export * from $MODULE
# 型export(TypeScript)
- pattern: export type $TYPE = $DEF
- pattern: export interface $INTERFACE { $$ }
---
# 4. 特定の関数シグネチャ検索
# CLI: ast-grep -p 'function $NAME(req, res) { $$ }' src/
id: find-express-handlers
language: JavaScript
rule:
any:
- pattern: function $NAME(req, res) { $$BODY }
- pattern: const $NAME = (req, res) => { $$BODY }
- pattern: app.$METHOD($PATH, (req, res) => { $$BODY })
message: "Express ハンドラー関数"
---
# 5. 変数宣言の検索(任意の宣言タイプ)
# CLI: 複数パターンはYAMLでのみ対応
id: find-var-declarations
language: JavaScript
rule:
any:
- pattern: var $NAME = $VALUE
- pattern: let $NAME = $VALUE
- pattern: const $NAME = $VALUE
---
# 6. 特定のASTノード種別
# CLI: ast-grep --kind field_definition src/
id: find-class-fields
language: JavaScript
rule:
kind: field_definition
---
# ==========================================
# 検索と置換
# ==========================================
# 7. オプショナルチェーンへの変換
# CLI: ast-grep -p '$PROP && $PROP()' --rewrite '$PROP?.()' --interactive src/
id: use-optional-chaining
language: TypeScript
rule:
pattern: $PROP && $PROP()
fix: $PROP?.()
---
# 8. console.logの削除
# CLI: ast-grep -p 'console.log($$)' --rewrite '' --interactive src/
id: remove-console-log
language: JavaScript
rule:
pattern: console.log($$ARGS)
fix: ""
message: "console.logは本番環境では削除してください"
---
# 9. 古いPromise構文を async/await に変換
# CLI: 複雑なため、YAMLでのみ対応
id: promise-to-async
language: JavaScript
rule:
pattern: $FUNC().then($CALLBACK)
fix: await $FUNC()
note: "コールバック関数の処理は手動で調整が必要です"
---
# ==========================================
# 関係性ルール(inside, has, follows, precedes)
# ==========================================
# 10. ループ内のawait検出
# CLI: 複雑なため、YAMLでのみ対応
id: no-await-in-loop
language: TypeScript
severity: warning
rule:
pattern: await $PROMISE
inside:
any:
- kind: for_statement
- kind: while_statement
- kind: for_in_statement
- kind: for_of_statement
stopBy: end
message: "ループ内でのawaitは性能問題を引き起こします"
---
# 11. 返り値のない関数検出
# CLI: 複雑なため、YAMLでのみ対応
id: function-without-return
language: JavaScript
rule:
pattern: function $NAME($$PARAMS) { $$BODY }
not:
has:
pattern: return $VALUE
---
# 12. try-catch内のconsole.log検出
# CLI: 複雑なため、YAMLでのみ対応
id: console-in-catch
language: JavaScript
rule:
pattern: console.log($MSG)
inside:
pattern: catch ($ERROR) { $$BODY }
selector: block
---
# ==========================================
# 正規表現とテキストマッチング
# ==========================================
# 13. React Hooks命名規則チェック
# CLI: 制約条件があるため、YAMLでのみ対応
id: react-hooks-naming
language: TypeScript
rule:
pattern: function $NAME($$) { $$ }
has:
any:
- pattern: useState($$)
- pattern: useEffect($$)
- pattern: useMemo($$)
constraints:
NAME:
regex: '^use[A-Z]'
not: true
message: "React Hooksは'use'で始まる必要があります"
---
# 14. TODOコメントの検出
# CLI: ast-grep -p '// TODO: $MSG' src/
id: find-todo-comments
language: JavaScript
rule:
regex: 'TODO:|FIXME:|HACK:'
kind: comment
---
# ==========================================
# 複合条件(all, any, not)
# ==========================================
# 15. 特定の条件を満たすif文
# CLI: 複雑なため、YAMLでのみ対応
id: suspicious-if-statement
language: JavaScript
rule:
all:
- pattern: if ($CONDITION) { $BODY }
- has:
pattern: $CONDITION
regex: '==|!='
not:
has:
pattern: $CONDITION
regex: '===|!=='
message: "厳密等価演算子(===, !==)を使用してください"
---
# 16. 空のcatch文
# CLI: ast-grep -p 'catch ($ERROR) {}' src/
id: empty-catch-block
language: JavaScript
rule:
all:
- pattern: catch ($ERROR) { $$BODY }
- not:
has:
any:
- kind: expression_statement
- kind: throw_statement
- kind: return_statement
---
# ==========================================
# 位置指定(nthChild)
# ==========================================
# 17. 配列の最初の要素
# CLI: 位置指定はYAMLでのみ対応
id: first-array-element
language: JavaScript
rule:
kind: string
nthChild: 1
inside:
kind: array
---
# 18. 関数の第2引数
# CLI: 位置指定はYAMLでのみ対応
id: second-function-argument
language: JavaScript
rule:
nthChild: 2
inside:
kind: arguments
---
# ==========================================
# ユーティリティルールの活用
# ==========================================
# 19. 共通パターンの定義と再利用
# CLI: ユーティリティルールはYAMLでのみ対応
utils:
is-literal:
any:
- kind: string
- kind: number
- kind: boolean
- kind: null
- kind: undefined
is-console-method:
pattern: console.$METHOD($$ARGS)
is-react-component:
any:
- pattern: function $NAME() { return $JSX }
- pattern: const $NAME = () => $JSX
- pattern: class $NAME extends Component { $$ }
id: check-hardcoded-values
language: JavaScript
rule:
matches: is-literal
inside:
matches: is-react-component
message: "コンポーネント内でハードコードされた値を使用しています"
---
# ==========================================
# 言語固有のパターン
# ==========================================
# 20. Python: print文をloggingに変換
# CLI: ast-grep -p 'print($MSG)' --rewrite 'logger.info($MSG)' --interactive *.py
id: use-logging-python
language: Python
rule:
pattern: print($MSG)
fix: logger.info($MSG)
---
# 21. Java: nullチェック不足
# CLI: 複雑なため、YAMLでのみ対応
id: missing-null-check
language: Java
rule:
pattern: $OBJ.$METHOD()
not:
precedes:
any:
- pattern: if ($OBJ != null)
- pattern: if (null != $OBJ)
- pattern: Objects.nonNull($OBJ)
---
# 22. Go: エラーハンドリング
# CLI: 複雑なため、YAMLでのみ対応
id: go-error-handling
language: Go
rule:
pattern: $VAR, err := $CALL
not:
follows:
pattern: if err != nil { $$ }
message: "エラーハンドリングが不足しています"
---
# ==========================================
# セキュリティパターン
# ==========================================
# 23. 危険なevalの使用
# CLI: ast-grep -p 'eval($CODE)' src/
id: dangerous-eval
language: JavaScript
severity: error
rule:
pattern: eval($CODE)
message: "evalの使用は危険です"
---
# 24. SQLインジェクションの可能性
# CLI: 複雑なため、YAMLでのみ対応
id: sql-injection-risk
language: JavaScript
rule:
pattern: $DB.query($QUERY)
has:
pattern: $QUERY
regex: '.*\+.*|.*\$\{.*\}.*'
message: "SQLインジェクションの可能性があります。パラメータ化クエリを使用してください"
---
# ==========================================
# パフォーマンスパターン
# ==========================================
# 25. ループ内のDOM操作
# CLI: 複雑なため、YAMLでのみ対応
id: dom-in-loop
language: JavaScript
rule:
pattern: document.$METHOD($$)
inside:
any:
- kind: for_statement
- kind: while_statement
- kind: for_in_statement
message: "ループ内でのDOM操作は性能問題を引き起こします"
---
# 26. 不要なre-render(React)
# CLI: 複雑なため、YAMLでのみ対応
id: unnecessary-rerender
language: TypeScript
rule:
pattern: useEffect(() => { $$BODY }, [])
has:
pattern: setState($VALUE)
message: "useEffect内でのstate更新は無限ループを引き起こす可能性があります"
---
# ==========================================
# コード品質パターン
# ==========================================
# 27. 長すぎる関数
# CLI: 複雑なため、YAMLでのみ対応
id: long-function
language: JavaScript
rule:
pattern: function $NAME($$) { $$BODY }
constraints:
BODY:
regex: '(\n.*){20,}'
message: "関数が長すぎます。分割を検討してください"
---
# 28. マジックナンバー
# CLI: ast-grep -p '$VAR > 100' src/ (具体的な数値指定)
id: magic-numbers
language: JavaScript
rule:
kind: number
regex: '^(?!0|1|2|10|100).*'
not:
inside:
kind: const_statement
message: "マジックナンバーは定数として定義してください"
---
# ==========================================
# 実行用の設定例
# ==========================================
# プロジェクト全体をチェック
# CLI: ast-grep scan
# 特定のルールのみ実行
# CLI: ast-grep scan -r specific-rule.yml
# インタラクティブ修正
# CLI: ast-grep scan --interactive
# JSON出力
# CLI: ast-grep scan --json | jq
# デバッグモード
# CLI: ast-grep run --debug-query -p 'pattern'
# ==========================================
# Basic Pattern Matching
# ==========================================
# 1. Function call search
# CLI: ast-grep -p 'console.log($MSG)' src/
id: find-console-log
language: JavaScript
rule:
pattern: console.log($MSG)
---
# 2. Function definition search (various patterns)
# CLI: ast-grep -p 'function $NAME($$$) { $$$$ }' src/
id: find-function-definitions
language: JavaScript
rule:
any:
# Regular function definition
- pattern: function $NAME($$$PARAMS) { $$$BODY }
# Arrow function (block form)
- pattern: const $NAME = ($$$PARAMS) => { $$$BODY }
# Arrow function (expression form)
- pattern: const $NAME = ($$$PARAMS) => $EXPR
# Object method
- pattern: $NAME($$$PARAMS) { $$$BODY }
# Class method
- pattern: |
class $CLASS {
$NAME($$$PARAMS) { $$$BODY }
}
# Async function
- pattern: async function $NAME($$$PARAMS) { $$$BODY }
- pattern: const $NAME = async ($$$PARAMS) => { $$$BODY }
---
# 3. Exported symbols search
# CLI: ast-grep -p 'export $SYMBOL' src/
id: find-exported-symbols
language: JavaScript
rule:
any:
# Named export
- pattern: export { $$$SYMBOLS }
# Default export (function)
- pattern: export default function $NAME($$$) { $$$$ }
# Default export (variable)
- pattern: export default $VALUE
# Export with declaration
- pattern: export const $NAME = $VALUE
- pattern: export function $NAME($$$) { $$$$ }
- pattern: export class $NAME { $$$$ }
# Re-export
- pattern: export { $$$SYMBOLS } from $MODULE
- pattern: export * from $MODULE
# Type export (TypeScript)
- pattern: export type $TYPE = $DEF
- pattern: export interface $INTERFACE { $$$$ }
---
# 4. Specific function signature search
# CLI: ast-grep -p 'function $NAME(req, res) { $$$$ }' src/
id: find-express-handlers
language: JavaScript
rule:
any:
- pattern: function $NAME(req, res) { $$$BODY }
- pattern: const $NAME = (req, res) => { $$$BODY }
- pattern: app.$METHOD($PATH, (req, res) => { $$$BODY })
message: "Express handler function"
---
# 5. Variable declaration search (any declaration type)
# CLI: Multiple patterns only supported in YAML
id: find-var-declarations
language: JavaScript
rule:
any:
- pattern: var $NAME = $VALUE
- pattern: let $NAME = $VALUE
- pattern: const $NAME = $VALUE
---
# 6. Specific AST node kind
# CLI: ast-grep --kind field_definition src/
id: find-class-fields
language: JavaScript
rule:
kind: field_definition
---
# ==========================================
# Search and Replace
# ==========================================
# 7. Convert to optional chaining
# CLI: ast-grep -p '$PROP && $PROP()' --rewrite '$PROP?.()' --interactive src/
id: use-optional-chaining
language: TypeScript
rule:
pattern: $PROP && $PROP()
fix: $PROP?.()
---
# 8. Remove console.log
# CLI: ast-grep -p 'console.log($$$)' --rewrite '' --interactive src/
id: remove-console-log
language: JavaScript
rule:
pattern: console.log($$$ARGS)
fix: ""
message: "console.log should be removed in production"
---
# 9. Convert old Promise syntax to async/await
# CLI: Complex pattern, YAML only
id: promise-to-async
language: JavaScript
rule:
pattern: $FUNC().then($CALLBACK)
fix: await $FUNC()
note: "Callback function handling requires manual adjustment"
---
# ==========================================
# Relational Rules (inside, has, follows, precedes)
# ==========================================
# 10. Detect await in loops
# CLI: Complex pattern, YAML only
id: no-await-in-loop
language: TypeScript
severity: warning
rule:
pattern: await $PROMISE
inside:
any:
- kind: for_statement
- kind: while_statement
- kind: for_in_statement
- kind: for_of_statement
stopBy: end
message: "await in loops can cause performance issues"
---
# 11. Functions without return value
# CLI: Complex pattern, YAML only
id: function-without-return
language: JavaScript
rule:
pattern: function $NAME($$$PARAMS) { $$$BODY }
not:
has:
pattern: return $VALUE
---
# 12. console.log in try-catch
# CLI: Complex pattern, YAML only
id: console-in-catch
language: JavaScript
rule:
pattern: console.log($MSG)
inside:
pattern: catch ($ERROR) { $$$BODY }
selector: block
---
# ==========================================
# Regular Expression and Text Matching
# ==========================================
# 13. React Hooks naming convention check
# CLI: Constraints required, YAML only
id: react-hooks-naming
language: TypeScript
rule:
pattern: function $NAME($$$) { $$$$ }
has:
any:
- pattern: useState($$$)
- pattern: useEffect($$$)
- pattern: useMemo($$$)
constraints:
NAME:
regex: '^use[A-Z]'
not: true
message: "React Hooks must start with 'use'"
---
# 14. TODO comment detection
# CLI: ast-grep -p '// TODO: $MSG' src/
id: find-todo-comments
language: JavaScript
rule:
regex: 'TODO:|FIXME:|HACK:'
kind: comment
---
# ==========================================
# Composite Conditions (all, any, not)
# ==========================================
# 15. Suspicious if statements
# CLI: Complex pattern, YAML only
id: suspicious-if-statement
language: JavaScript
rule:
all:
- pattern: if ($CONDITION) { $BODY }
- has:
pattern: $CONDITION
regex: '==|!='
not:
has:
pattern: $CONDITION
regex: '===|!=='
message: "Use strict equality operators (===, !==)"
---
# 16. Empty catch blocks
# CLI: ast-grep -p 'catch ($ERROR) {}' src/
id: empty-catch-block
language: JavaScript
rule:
all:
- pattern: catch ($ERROR) { $$$BODY }
- not:
has:
any:
- kind: expression_statement
- kind: throw_statement
- kind: return_statement
---
# ==========================================
# Position Specification (nthChild)
# ==========================================
# 17. First array element
# CLI: Position specification only in YAML
id: first-array-element
language: JavaScript
rule:
kind: string
nthChild: 1
inside:
kind: array
---
# 18. Second function argument
# CLI: Position specification only in YAML
id: second-function-argument
language: JavaScript
rule:
nthChild: 2
inside:
kind: arguments
---
# ==========================================
# Utility Rule Usage
# ==========================================
# 19. Common pattern definition and reuse
# CLI: Utility rules only in YAML
utils:
is-literal:
any:
- kind: string
- kind: number
- kind: boolean
- kind: null
- kind: undefined
is-console-method:
pattern: console.$METHOD($$$ARGS)
is-react-component:
any:
- pattern: function $NAME() { return $JSX }
- pattern: const $NAME = () => $JSX
- pattern: class $NAME extends Component { $$$$ }
id: check-hardcoded-values
language: JavaScript
rule:
matches: is-literal
inside:
matches: is-react-component
message: "Hardcoded values used in component"
---
# ==========================================
# Language-Specific Patterns
# ==========================================
# 20. Python: Convert print to logging
# CLI: ast-grep -p 'print($MSG)' --rewrite 'logger.info($MSG)' --interactive *.py
id: use-logging-python
language: Python
rule:
pattern: print($MSG)
fix: logger.info($MSG)
---
# 21. Java: Missing null check
# CLI: Complex pattern, YAML only
id: missing-null-check
language: Java
rule:
pattern: $OBJ.$METHOD()
not:
precedes:
any:
- pattern: if ($OBJ != null)
- pattern: if (null != $OBJ)
- pattern: Objects.nonNull($OBJ)
---
# 22. Go: Error handling
# CLI: Complex pattern, YAML only
id: go-error-handling
language: Go
rule:
pattern: $VAR, err := $CALL
not:
follows:
pattern: if err != nil { $$$$ }
message: "Missing error handling"
---
# ==========================================
# Security Patterns
# ==========================================
# 23. Dangerous eval usage
# CLI: ast-grep -p 'eval($CODE)' src/
id: dangerous-eval
language: JavaScript
severity: error
rule:
pattern: eval($CODE)
message: "eval usage is dangerous"
---
# 24. SQL injection possibility
# CLI: Complex pattern, YAML only
id: sql-injection-risk
language: JavaScript
rule:
pattern: $DB.query($QUERY)
has:
pattern: $QUERY
regex: '.*\+.*|.*\$\{.*\}.*'
message: "Possible SQL injection. Use parameterized queries"
---
# ==========================================
# Performance Patterns
# ==========================================
# 25. DOM operations in loops
# CLI: Complex pattern, YAML only
id: dom-in-loop
language: JavaScript
rule:
pattern: document.$METHOD($$$)
inside:
any:
- kind: for_statement
- kind: while_statement
- kind: for_in_statement
message: "DOM operations in loops can cause performance issues"
---
# 26. Unnecessary re-render (React)
# CLI: Complex pattern, YAML only
id: unnecessary-rerender
language: TypeScript
rule:
pattern: useEffect(() => { $$$BODY }, [])
has:
pattern: setState($VALUE)
message: "State updates in useEffect can cause infinite loops"
---
# ==========================================
# Code Quality Patterns
# ==========================================
# 27. Functions that are too long
# CLI: Complex pattern, YAML only
id: long-function
language: JavaScript
rule:
pattern: function $NAME($$$) { $$$BODY }
constraints:
BODY:
regex: '(\n.*){20,}'
message: "Function is too long. Consider splitting"
---
# 28. Magic numbers
# CLI: ast-grep -p '$VAR > 100' src/ (specific number)
id: magic-numbers
language: JavaScript
rule:
kind: number
regex: '^(?!0|1|2|10|100).*'
not:
inside:
kind: const_statement
message: "Magic numbers should be defined as constants"
---
# ==========================================
# Execution Configuration Examples
# ==========================================
# Check entire project
# CLI: ast-grep scan
# Run specific rule only
# CLI: ast-grep scan -r specific-rule.yml
# Interactive fixing
# CLI: ast-grep scan --interactive
# JSON output
# CLI: ast-grep scan --json | jq
# Debug mode
# CLI: ast-grep run --debug-query -p 'pattern'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment