[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,88 +2,222 @@
|
||||
id: wiki-2026-0508-ast-traversal
|
||||
title: AST Traversal
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-CODING-001]
|
||||
aliases: [ast-walk, syntax-tree-traversal, visitor-pattern]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
tags: [coding, ast, compiler]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [ast, compilers, codemod, static-analysis]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: batch-reinforce-01
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: typescript
|
||||
framework: ts-morph
|
||||
---
|
||||
|
||||
# Abstract Syntax Tree Traversal
|
||||
# AST Traversal
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> 소스 코드의 추상적인 구조를 정의된 규칙에 따라 탐색하며 변환 및 분석의 기틀을 마련하는 컴파일러의 핵심 여정.
|
||||
## 매 한 줄
|
||||
> **"매 code 의 tree 의 walk 한다"**. 매 AST (Abstract Syntax Tree) traversal 의 compiler/linter/codemod/IDE 의 foundation. 매 2026 의 tree-sitter (Atom, 2018; 매 GitHub 의 sole semantic search engine) + ts-morph + Babel + RustPython AST 의 dominant tooling.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** 비지터 패턴(Visitor Pattern)을 활용하여 데이터 구조와 알고리즘을 분리하고 트리 노드를 순회하는 재귀적 처리 패턴.
|
||||
- **세부 내용:**
|
||||
- 전위/중위/후위 순회를 통한 코드 분석 시점 최적화.
|
||||
- 정적 분석 및 린팅(Linting) 툴의 기초 로직 제공.
|
||||
- 리팩토링 및 코드 자동 생성 도구의 엔진 역할.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 단순 텍스트 기반 검색과 달리 문맥(Context)을 이해하는 구조적 접근의 필수성 강조.
|
||||
- **정책 변화:** 코딩 표준(w1) 강화에 따라 AST 기반 자동 수정 가중치 상향.
|
||||
### 매 traversal strategies
|
||||
- **Pre-order DFS**: 매 visit parent → children. 매 default (most visitors).
|
||||
- **Post-order DFS**: 매 visit children → parent. 매 type inference, dead-code elim.
|
||||
- **BFS**: 매 level-by-level. 매 rare — scope analysis.
|
||||
- **Visitor pattern**: 매 node-type-keyed callbacks. 매 ESLint, Babel, ts-morph standard.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Parent:** 10_Wiki/💡 Topics/Coding
|
||||
- **Related:** [[CST|CST]], [[Parser|Parser]], Visitor-Pattern
|
||||
- **Raw Source:** 00_Raw/2026-04-20/[[Abstract-Syntax-Tree-Traversal|Abstract-Syntax-Tree-Traversal]].md
|
||||
### 매 mutating vs read-only
|
||||
- **Read-only**: linter, complexity metrics, security scanner.
|
||||
- **Mutating**: codemod, formatter, transpiler. 매 immutability + new tree 의 produce 의 best-practice (Babel: `path.replaceWith`).
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. ESLint rule — 매 pattern detection.
|
||||
2. Codemod — jscodeshift, ts-morph, ast-grep.
|
||||
3. Tree-sitter query — 매 IDE syntax highlight, code nav.
|
||||
4. AST-based diffing — 매 difftastic, semantic diff.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### Babel visitor (JavaScript)
|
||||
```js
|
||||
import { parse } from '@babel/parser';
|
||||
import traverse from '@babel/traverse';
|
||||
import generate from '@babel/generator';
|
||||
import * as t from '@babel/types';
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
const code = `console.log("hello"); foo("world");`;
|
||||
const ast = parse(code);
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
traverse(ast, {
|
||||
CallExpression(path) {
|
||||
const callee = path.node.callee;
|
||||
if (t.isMemberExpression(callee) &&
|
||||
t.isIdentifier(callee.object, { name: 'console' })) {
|
||||
// strip console.* calls
|
||||
path.remove();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
console.log(generate(ast).code); // foo("world");
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### ts-morph (TypeScript refactor)
|
||||
```ts
|
||||
import { Project, SyntaxKind } from 'ts-morph';
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
const project = new Project({ tsConfigFilePath: 'tsconfig.json' });
|
||||
for (const sf of project.getSourceFiles()) {
|
||||
sf.forEachDescendant(node => {
|
||||
if (node.getKind() === SyntaxKind.CallExpression) {
|
||||
const ce = node.asKindOrThrow(SyntaxKind.CallExpression);
|
||||
if (ce.getExpression().getText() === 'fetch') {
|
||||
ce.replaceWithText(`httpClient.${ce.getText().replace('fetch', '')}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
await project.save();
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Python — `ast` + NodeTransformer
|
||||
```python
|
||||
import ast
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
class StripPrint(ast.NodeTransformer):
|
||||
def visit_Expr(self, node):
|
||||
if (isinstance(node.value, ast.Call)
|
||||
and isinstance(node.value.func, ast.Name)
|
||||
and node.value.func.id == "print"):
|
||||
return None # remove
|
||||
return node
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
src = "print('hi')\nx = 1"
|
||||
tree = ast.parse(src)
|
||||
StripPrint().visit(tree)
|
||||
ast.fix_missing_locations(tree)
|
||||
print(ast.unparse(tree)) # x = 1
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### tree-sitter query (multi-language)
|
||||
```scheme
|
||||
; queries/python/calls.scm — find all decorated functions
|
||||
(decorated_definition
|
||||
(decorator (call function: (identifier) @decorator-name))
|
||||
definition: (function_definition name: (identifier) @func-name))
|
||||
```
|
||||
|
||||
```python
|
||||
import tree_sitter_python as tspython
|
||||
from tree_sitter import Language, Parser, Query
|
||||
|
||||
PY = Language(tspython.language())
|
||||
parser = Parser(PY)
|
||||
tree = parser.parse(b"@app.route('/')\ndef home(): pass")
|
||||
q = Query(PY, open("queries/python/calls.scm").read())
|
||||
for node, name in q.captures(tree.root_node):
|
||||
print(name, node.text)
|
||||
```
|
||||
|
||||
### ast-grep (rule-based, polyglot)
|
||||
```yaml
|
||||
# rule.yml
|
||||
id: no-console-log
|
||||
language: js
|
||||
rule:
|
||||
pattern: console.log($$$)
|
||||
fix: ''
|
||||
```
|
||||
|
||||
```bash
|
||||
ast-grep scan -r rule.yml --update
|
||||
```
|
||||
|
||||
### Rust — syn (proc-macro / codegen)
|
||||
```rust
|
||||
use syn::{visit::Visit, ItemFn, File};
|
||||
|
||||
struct FnCounter(usize);
|
||||
impl<'ast> Visit<'ast> for FnCounter {
|
||||
fn visit_item_fn(&mut self, i: &'ast ItemFn) {
|
||||
self.0 += 1;
|
||||
syn::visit::visit_item_fn(self, i);
|
||||
}
|
||||
}
|
||||
|
||||
let src = std::fs::read_to_string("src/lib.rs").unwrap();
|
||||
let file: File = syn::parse_file(&src).unwrap();
|
||||
let mut c = FnCounter(0);
|
||||
c.visit_file(&file);
|
||||
println!("functions: {}", c.0);
|
||||
```
|
||||
|
||||
### ESLint custom rule
|
||||
```js
|
||||
module.exports = {
|
||||
meta: { type: 'problem', schema: [] },
|
||||
create(ctx) {
|
||||
return {
|
||||
'CallExpression[callee.name="eval"]'(node) {
|
||||
ctx.report({ node, message: 'eval is forbidden' });
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### Pre-order vs post-order (manual walk)
|
||||
```ts
|
||||
function walkPre(node: Node, fn: (n: Node) => void) {
|
||||
fn(node);
|
||||
for (const c of node.children) walkPre(c, fn);
|
||||
}
|
||||
function walkPost(node: Node, fn: (n: Node) => void) {
|
||||
for (const c of node.children) walkPost(c, fn);
|
||||
fn(node);
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| Goal | Tool |
|
||||
|---|---|
|
||||
| JS/TS lint rule | ESLint visitor |
|
||||
| TS large refactor | ts-morph |
|
||||
| Python codemod | LibCST (preserves whitespace) > ast |
|
||||
| Polyglot pattern search | ast-grep, Semgrep |
|
||||
| IDE / syntax highlight | tree-sitter |
|
||||
| Rust macro | syn / quote |
|
||||
| Babel plugin | @babel/traverse |
|
||||
|
||||
**기본값**: 매 ts-morph (TS refactor) · ast-grep (polyglot scan) · LibCST (Python codemod).
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Compilers]] · [[Static-Analysis]]
|
||||
- 변형: [[Codemod]] · [[Tree-Sitter]] · [[Visitor-Pattern]]
|
||||
- 응용: [[ESLint]] · [[Refactoring]]
|
||||
- Adjacent: [[Architectural-Constraint-Enforcement]] · [[Architecture_Refactor]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 codebase 의 LLM-driven structural query — 매 ast-grep + Claude 의 hybrid (LLM 의 generate pattern, ast 의 execute).
|
||||
**언제 X**: 매 LLM 의 raw text find/replace — 매 AST-aware tool 의 사용.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Regex on code**: 매 multiline construct 의 break — 매 AST 의 사용.
|
||||
- **Mutating during traversal**: 매 visitor 의 reentrancy bug — 매 collect-then-apply.
|
||||
- **Ignore comments/whitespace**: 매 codemod 의 lose comments — 매 LibCST/Recast 의 사용.
|
||||
- **Single-pass dependence**: 매 transformation order 의 fragile — 매 idempotent 의 design.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Babel docs; ts-morph guide; tree-sitter playground; *Crafting Interpreters* — Nystrom).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Babel/ts-morph/tree-sitter/ast-grep patterns |
|
||||
|
||||
Reference in New Issue
Block a user