[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
+142 -87
View File
@@ -1,116 +1,171 @@
---
id: wiki-2026-0508-abstract-syntax-tree
title: Abstract Syntax Tree
title: Abstract Syntax Tree (AST)
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [P-REINFORCE-WIKI-DEV-AST, AST, 추상 구문 트리, Abstract Syntax Tree, 구문 분석, 파싱 트리]
aliases: [AST, Syntax Tree, Parse Tree (informal)]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [Static_Analysis, Compilers, Parsing, Code_Modeling, Review]
raw_sources: [Datacollector_Export_2026-05-02]
last_reinforced: 2026-05-02
confidence_score: 0.95
verification_status: applied
tags: [compiler, parsing, ast, language-tooling, static-analysis]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: Python/JavaScript/Rust
framework: ast/Babel/swc/tree-sitter
---
# [[추상 구문 트리와 정적 코드 분석 원리 (AST)]]
# Abstract Syntax Tree (AST)
## 1. 개요
추상 구문 트리(AST, Abstract Syntax Tree)는 프로그래밍 언어로 작성된 소스 코드의 추상적인 구문 구조를 트리 형태로 표현한 자료구조다. 실제 코드의 세세한 문법적 요소(괄호, 세미콜론 등)를 배제하고 코드의 논리적인 구조와 관계에 집중함으로써, 컴파일러, 정적 분석 도구, 린터(Linter) 등이 코드를 기계적으로 해독하고 변환하는 핵심 기반이 된다.
## 매 한 줄
> **"매 source code 의 tree shape, syntax noise 의 strip"**. AST = parser 의 output, 매 token sequence 의 hierarchical node tree (FunctionDecl, BinaryExpr, ...) 로 변환. 매 compiler/linter/formatter/codemod/LLM-codegen 의 foundation — 매 2026 LLM agentic coding 의 매 ground truth structural layer.
## 2. 주요 역할 및 활용
- **코드 구조 모델링**: 변수 선언, 함수 호출, 제어 흐름 등 코드의 구성 요소를 노드(Node)와 엣지(Edge)로 구조화하여 전체적인 아키텍처 파악 지원.
- **정적 분석 (Static Analysis)**: 코드를 실행하지 않고도 AST를 탐색하여 잠재적인 런타임 버그(탐지율 약 42~48%), 보안 취약점, 코딩 컨벤션 위반 사항 식별.
- **코드 변환 및 트랜스파일링**: 원본 AST를 다른 언어나 최적화된 형태의 AST로 변환(예: Babel을 통한 JS 버전 변환).
- **AI 기반 코드 리뷰**: 현대적인 AI 코드 리뷰 도구는 AST를 통해 코드의 맥락을 파악하고, 단순 텍스트 비교를 넘어선 심층적인 로직 검증 및 자동 수정(Auto-fix) 제안 수행.
## 매 핵심
## 3. 엔지니어링 가치
- **정밀한 버그 탐지**: 단순 정규 표현식 기반 검색으로는 찾아내기 힘든 복잡한 논리 결함을 코드 계층 구조 분석을 통해 정확히 식별.
- **개발 생산성 향상**: 자동화된 린터와 분석기가 1차적으로 결함을 걸러줌으로써, 인간 리뷰어는 비즈니스 로직과 아키텍처 정렬(Alignment) 등 고수준 의사결정에 집중 가능.
- **언어 독립적 분석 인프라**: 소스 코드를 표준화된 트리 구조로 변환함으로써, 다양한 프로그래밍 언어에 대해 일관된 분석 규칙 적용 가능.
### 매 vs Concrete Syntax Tree (CST)
- **CST (parse tree)**: 매 every token (paren, semicolon, whitespace) 의 retain.
- **AST**: 매 semantically meaningful node only — 매 cosmetic 의 drop.
- 매 modern formatter (Prettier, rustfmt) 의 CST-like (lossless) 의 use, 매 compiler/codemod 의 AST.
## 4. 트레이드오프 및 주의사항
- **인간 검증의 필수성**: AST 분석은 강력하지만 완벽하지 않다. 분석기가 제안한 수정안이 실제 비즈니스 의도나 성능 요구사항에 부합하는지 최종적으로는 인간의 검토가 수반되어야 함.
- **구문 분석 오버헤드**: 방대한 코드베이스 전체를 AST로 변환하고 탐색하는 과정에서 메모리와 CPU 자원이 소모되므로, 효율적인 증분 분석(Incremental Analysis) 기법 도입 고려.
- **언어별 문법 대응**: 프로그래밍 언어의 버전이 업데이트될 때마다 파서(Parser)를 최신 문법에 맞게 동기화해야 하는 유지보수 비용 발생.
### 매 node anatomy
- **type**: `BinaryExpression`, `FunctionDeclaration`, ...
- **children**: structured field (`left`, `right`, `body`, `params`).
- **location**: `start`/`end` byte offset + line/col — 매 error message + source map.
## 5. 지식 연결 (Related)
- [[Code_Property_Graph]]: AST를 확장하여 데이터 흐름과 제어 흐름을 통합한 모델.
- [[Automated_Code_Analysis]]: AST를 기반으로 동작하는 자동화 도구 생태계.
- [[Static_Application_Security_Testing]]: AST 분석이 보안 관점에서 응용되는 분야.
### 매 typical pipeline
1. **Lex** → token stream.
2. **Parse** → AST.
3. **Analyze** (type check, scope resolve).
4. **Transform** (optimize, lower).
5. **Emit** (codegen, print).
## 🧪 검증 상태 (Validation)
- **정보 상태**: 검증 완료 (Verified)
- **출처 신뢰도**: A
- **검토 이유**: 소프트웨어를 정적·구조적으로 해독하고 자동화된 품질 보증 체계를 구축하기 위한 컴퓨터 과학 기반의 표준 모델 정립.
### 매 응용
1. Compiler (rustc, tsc, clang) 의 IR upstream.
2. Linter (ESLint, ruff, clippy) — 매 rule = AST pattern match.
3. Formatter (Prettier, Black, gofmt).
4. Codemod (jscodeshift, ts-morph, libcst) — 매 large refactor.
5. LLM agentic coding (Claude Opus 4.7 의 tree-sitter grounding).
6. Static analysis / SAST (Semgrep, CodeQL).
7. IDE (LSP, syntax highlight, jump-to-def).
## 📌 한 줄 통찰 (The Karpathy Summary)
## 💻 패턴
> *(TODO: 한 문장으로 핵심 통찰을 작성. "X는 Y 조건에서 Z 효과를 낸다" 구조 권장.)*
### Python `ast` — visit + transform
```python
import ast
## 📖 구조화된 지식 (Synthesized Content)
src = "x = 1 + 2 * 3"
tree = ast.parse(src)
**추출된 패턴:**
> *(TODO)*
class ConstFold(ast.NodeTransformer):
def visit_BinOp(self, node: ast.BinOp):
self.generic_visit(node)
if isinstance(node.left, ast.Constant) and isinstance(node.right, ast.Constant):
try:
return ast.copy_location(ast.Constant(value=eval(compile(ast.Expression(node), "", "eval"))), node)
except Exception:
pass
return node
**세부 내용:**
- *(TODO)*
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
## 🔗 지식 연결 (Graph)
- **Parent:** [[10_Wiki/Topics]]
- **Related:** *(TODO: 최소 2개)*
- **Opposite / Trade-off:** *(TODO)*
- **Raw Source:** 직접 입력
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
new = ast.fix_missing_locations(ConstFold().visit(tree))
print(ast.unparse(new)) # x = 7
```
## 🤔 의사결정 기준 (Decision Criteria)
### tree-sitter (multi-language, incremental)
```python
from tree_sitter import Language, Parser
import tree_sitter_python as tspy
**선택 A를 써야 할 때:**
- *(TODO)*
PY = Language(tspy.language())
parser = Parser(PY)
tree = parser.parse(b"def add(a, b):\n return a + b\n")
root = tree.root_node
for n in root.children:
print(n.type, n.start_point, n.end_point)
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Babel codemod (JS/TS)
```js
import * as t from "@babel/types";
import generate from "@babel/generator";
import { parse } from "@babel/parser";
import traverse from "@babel/traverse";
**기본값:**
> *(TODO)*
const ast = parse(`var x = 1;`, { sourceType: "module" });
traverse(ast, {
VariableDeclaration(path) {
if (path.node.kind === "var") path.node.kind = "const";
},
});
console.log(generate(ast).code); // const x = 1;
```
## ❌ 안티패턴 (Anti-Patterns)
### Rust `syn` — proc macro
```rust
use syn::{parse_quote, ItemFn};
use quote::quote;
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
let f: ItemFn = parse_quote! { fn greet() { println!("hi"); } };
let name = &f.sig.ident;
let out = quote! { #f impl Greeter for () { fn name() -> &'static str { stringify!(#name) } } };
```
### Pattern match (Semgrep-style)
```yaml
rules:
- id: dangerous-eval
pattern: eval($X)
message: avoid eval
languages: [python]
severity: ERROR
```
### LLM-grounded edit (2026)
```python
# 매 LLM 의 line-range edit instead of free-form rewrite — AST 의 anchor
edit = {"file": "app.py", "node_path": "Module/FunctionDef[name=handler]/body[2]",
"replace_with": "return JSONResponse({'ok': True})"}
apply_ast_edit(edit) # 매 syntactic safety guaranteed
```
## 매 결정 기준
| 상황 | Tool |
|---|---|
| Single-language Python script tooling | `ast` (stdlib) |
| Multi-language, incremental (editor) | tree-sitter |
| JS/TS large codemod | jscodeshift / ts-morph |
| Python lossless refactor (preserves comments) | LibCST |
| Compiler frontend, type-aware codemod | language native (rustc API, tsc API) |
| Cross-repo security scan | Semgrep / CodeQL |
**기본값**: 매 cross-language tooling — tree-sitter. Python-only — `ast` + LibCST.
## 🔗 Graph
- 부모: [[Compiler]] · [[Programming Language Theory]]
- 변형: [[Concrete Syntax Tree]] · [[HIR]] · [[MIR]] · [[SSA]]
- 응용: [[Linter]] · [[Codemod]] · [[Static Analysis]] · [[LSP]] · [[Tree-sitter]]
- Adjacent: [[Lexer]] · [[Parser Combinator]] · [[Visitor Pattern]]
## 🤖 LLM 활용
**언제**: 매 codemod, 매 lint rule, 매 LLM-output 의 syntactic validation, 매 IDE refactor.
**언제 X**: 매 trivial regex match 의 sufficient case (e.g. `TODO` find).
## ❌ 안티패턴
- **Regex 의 code 의 parse**: 매 nested/quoted/comment 의 always break — 매 AST 의 use.
- **Mutate while iterating**: 매 child traversal 중 parent mutate — 매 transformer pattern (return new node).
- **Lose source location**: 매 error message 의 useless 의 됨 — 매 location preserve.
- **Print round-trip 의 trust**: 매 unparse 의 lossy (whitespace, comment) — 매 LibCST/Prettier 의 use.
## 🧪 검증 / 중복
- Verified (Aho et al. *Dragon Book* 2nd ed; Python ast docs; tree-sitter docs 2025; Babel handbook).
- 신뢰도 A.
- AST(Abstract_Syntax_Tree).md 의 redirect.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — canonical AST 문서, tree-sitter/LLM-grounded edit 추가 |