--- id: wiki-20260508-ast-abstract-syntax-tree--redir title: AST (Abstract Syntax Tree) category: 10_Wiki/Topics status: verified canonical_id: self aliases: [AST, Abstract Syntax Tree, 추상 구문 트리] duplicate_of: none source_trust_level: A confidence_score: 0.92 verification_status: applied tags: [compiler, parser, ast, language] raw_sources: [] last_reinforced: 2026-05-10 github_commit: pending tech_stack: language: typescript framework: babel-parser, ts-morph, tree-sitter --- # AST (Abstract Syntax Tree) ## 매 한 줄 > **"매 source code 의 tree-shaped semantic skeleton"**. 매 lexer 의 token stream 을 parser 가 grammar rule 따라 nested node 의 tree 로 변환 — comment/whitespace/parens 의 trivia 를 제거하고 매 program 의 structural meaning 만 보존. 매 2026 의 Babel·SWC·TypeScript Compiler·Tree-sitter·Rust analyzer 의 모든 modern toolchain 의 핵심 IR. ## 매 핵심 ### 매 AST vs CST - **CST** (Concrete Syntax Tree): 매 source 의 every char 보존 — formatter, linter용. - **AST**: 매 semantic structure 만 — compiler, transpiler, type checker용. - 매 trade-off: lossless ↔ analysis-friendly. ### 매 Node 의 구조 - 매 `type` field (e.g. `BinaryExpression`, `Identifier`). - 매 children (positional or named). - 매 `loc`/`range` (source position). - 매 ESTree spec — JS 의 standard AST shape. ### 매 응용 1. **Compiler**: AST → IR → bytecode/machine code. 2. **Transpiler** (Babel, SWC): AST → transformed AST → code. 3. **Linter** (ESLint): AST traversal + rule matching. 4. **Formatter** (Prettier): AST → printer. 5. **IDE**: hover, refactor, go-to-def 의 AST query. 6. **Codemod** (jscodeshift, ts-morph): bulk refactor. ## 💻 패턴 ### Babel parse ```typescript import { parse } from "@babel/parser"; const code = `const x = 1 + 2;`; const ast = parse(code, { sourceType: "module" }); console.log(ast.program.body[0]); // VariableDeclaration { kind: "const", declarations: [...] } ``` ### Visitor (transform) ```typescript import traverse from "@babel/traverse"; traverse(ast, { BinaryExpression(path) { if (path.node.operator === "+") { // 매 constant folding const { left, right } = path.node; if (left.type === "NumericLiteral" && right.type === "NumericLiteral") { path.replaceWith({ type: "NumericLiteral", value: left.value + right.value }); } } }, }); ``` ### TypeScript Compiler API ```typescript import * as ts from "typescript"; const source = ts.createSourceFile("x.ts", "const x: number = 1;", ts.ScriptTarget.Latest); function visit(node: ts.Node) { if (ts.isVariableDeclaration(node)) { console.log(node.name.getText(source)); } ts.forEachChild(node, visit); } visit(source); ``` ### Tree-sitter (incremental) ```javascript const Parser = require("tree-sitter"); const TS = require("tree-sitter-typescript").typescript; const parser = new Parser(); parser.setLanguage(TS); const tree = parser.parse("const x = 1;"); // 매 incremental: tree.edit(...) 로 partial reparse ``` ### ts-morph (codemod) ```typescript import { Project } from "ts-morph"; const proj = new Project(); const sf = proj.addSourceFileAtPath("src/foo.ts"); sf.getFunctions().forEach((fn) => fn.setIsAsync(true)); sf.saveSync(); ``` ## 매 결정 기준 | 상황 | Approach | |---|---| | Compile / transpile JS/TS | Babel (@babel/parser) or SWC | | IDE / editor highlighting | Tree-sitter (incremental, fast) | | TypeScript-specific 의 type-aware refactor | TypeScript Compiler API or ts-morph | | Linting | ESLint (espree/typescript-eslint) | | 1-off codemod | jscodeshift or ts-morph | | Native speed (Rust/Go) | SWC, Rome, Biome | **기본값**: 매 TS 의 type-aware 작업 → ts-morph. 매 perf-critical 의 transpile → SWC. 매 editor → Tree-sitter. ## 🔗 Graph - 부모: [[Parser]] - 응용: [[ESLint]] · [[Prettier]] ## 🤖 LLM 활용 **언제**: 매 codemod 의 generation, AST node type 의 explanation, visitor pattern 의 boilerplate. **언제 X**: 매 large-scale 의 type-aware refactor — ts-morph 의 deterministic 가 더 안전. ## ❌ 안티패턴 - **Regex 의 code 의 transform**: 매 nested syntax 의 break — AST 의 use. - **Mutate AST 의 children array 의 직접**: 매 visitor 의 path API 의 use. - **Source map 의 무시**: 매 transform 후 의 debug 의 broken — `retainLines`/sourcemap 의 emit. ## 🧪 검증 / 중복 - Verified (Babel docs, TS Compiler API, ESTree spec). - 신뢰도 A. ## 🕓 Changelog | 날짜 | 변경 | |---|---| | 2026-05-08 | Phase 1 | | 2026-05-10 | Manual cleanup — full AST treatment with Babel/TS/Tree-sitter patterns |