[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,92 +2,152 @@
|
||||
id: wiki-2026-0508-concrete-syntax-tree-cst
|
||||
title: Concrete Syntax Tree (CST)
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-858963]
|
||||
aliases: [Parse Tree, CST, Lossless Syntax Tree]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
verification_status: applied
|
||||
tags: [parser, ast, tooling, language-engineering]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - Concrete Syntax Tree (CST)"
|
||||
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: Rust/JS
|
||||
framework: tree-sitter/rowan
|
||||
---
|
||||
|
||||
# [[Concrete Syntax Tree (CST)|Concrete Syntax Tree (CST]]
|
||||
# Concrete Syntax Tree (CST)
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> Concrete Syntax Tree (CST)는 파스 트리(Parse Tree)라고도 불리며, 문맥 자유 문법(context-free grammar)의 트리 표현 형태로 컴파일러가 코드를 이해하는 방식을 보여주는 공식적인 구조이다 [1]. 추상 구문 트리(AST)와 달리 구문적 요소뿐만 아니라 미세한 문체, 어휘, 레이아웃(들여쓰기 등) 세부 사항까지 코드의 모든 측면을 정밀하게 포착한다 [2]. 이러한 구체적 특성 때문에 코드 포맷팅 등 소스 코드가 변환될 때 그 형태가 크게 변경되며, 최근 코드 작성자를 식별하는 기계 학습 기반의 코드 스타일로메트리(Code Stylometry) 모델에서 중요하게 활용되고 있다 [3, 4].
|
||||
## 매 한 줄
|
||||
> **"매 source 의 every token (whitespace, comment 포함) 까지 보존하는 lossless tree"**. AST 가 semantic-only 인 반면 CST 는 매 source 의 round-trip 가능. 매 modern tooling — tree-sitter, rowan (rust-analyzer), Roslyn — 매 CST 위에서 매 IDE feature, refactoring, formatter 를 매 build.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **정의 및 구조:** CST는 주어진 문법에 대해 각 노드가 특정 기호로 레이블링되는 순서 트리(ordered tree)이다 [1]. 루트 노드는 시작 기호로, 비단말(non-leaf) 노드들은 비단말 기호로 이루어지며 자식 노드들과의 관계는 문법의 생성 규칙을 정확하게 반영하여 구성된다 [5].
|
||||
- **AST와의 차이점:** 추상 구문 트리(AST)가 코드 파싱 후 레이아웃 특징 등을 추상화하여 배제하는 반면, CST는 코드를 포맷팅하거나 여백을 변경할 때의 레이아웃 정보까지 그대로 유지한다 [3, 6]. 따라서 코드를 다른 형태로 재정렬하는 소스-대-소스 변환 시 AST는 동일할 수 있지만, CST는 유의미하게 변경된다 [3].
|
||||
- **CST 경로(Path) 및 문맥 추출:** CST 내에서 두 단말 노드 사이를 위아래로 이동하는 시퀀스를 'CST 경로(CST path)'라고 정의한다 [7]. 이 경로와 시작 및 종료 노드의 실제 코드 토큰 값을 결합한 것을 '경로 문맥(path context)'이라 부르며, 코드의 어휘적, 구문적, 레이아웃적 특징을 유지하는 데이터 표현 수단으로 쓰인다 [8, 9].
|
||||
- **코드 분석 및 작성자 식별(Stylometry)에서의 활용:** 최신 기계 학습 모델(예: code2vec)은 코드의 의미론적 요소와 문체적 요소를 모두 보존하기 위해 AST 대신 CST를 입력값으로 사용한다 [4]. 실제 실험 결과, AST 대신 CST 기반의 코드 표현을 사용하면 레이아웃 정보가 반영되어 코드 작성자 식별(Authorship attribution)의 정확도가 크게 향상(51.00%에서 67.86%로 증가)되는 것으로 확인되었다 [10, 11].
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
|
||||
### 매 vs AST
|
||||
- **AST**: semantic node 만 (`if`, `BinaryOp`, etc) — comment, whitespace 버림.
|
||||
- **CST**: 모든 token + trivia 보존 — `source == reprint(cst)`.
|
||||
- CST → AST 의 lowering 가능, 역은 매 lossy.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** Abstract Syntax Tree (AST), Code Stylometry, Parse Tree
|
||||
- **Projects/Contexts:** 프로그래머의 코드 작성 스타일을 분석하여 작성자를 식별하는 코드 스타일로메트리 연구에서, 코드 포맷팅([[Formatting|Formatting]]) 및 축소(minification) 기술이 식별 정확도에 미치는 영향을 측정하기 위한 코드 표현 방식으로 사용됨 [3, 12, 13].
|
||||
- **Contradictions/Notes:** 소스에 관련 정보가 부족합니다.
|
||||
### 매 핵심 properties
|
||||
- **Lossless**: print 시 원본 byte-for-byte 복구.
|
||||
- **Error-tolerant**: incomplete/invalid code 도 partial tree.
|
||||
- **Incremental**: edit 시 affected subtree 만 reparse (tree-sitter).
|
||||
- **Untyped or weakly-typed**: 모든 node 가 동질 — typed wrapper 로 navigate.
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-19*
|
||||
### 매 응용
|
||||
1. IDE: syntax highlight, fold, outline, indent.
|
||||
2. Refactoring: rename, extract method (preserve formatting).
|
||||
3. Formatter: prettier, rustfmt — CST 로 layout 결정.
|
||||
4. Linter: tree-sitter queries.
|
||||
|
||||
---
|
||||
## 💻 패턴
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
### tree-sitter parsing
|
||||
```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: number = 1;');
|
||||
// Walk
|
||||
const cursor = tree.walk();
|
||||
do { console.log(cursor.nodeType, cursor.startIndex, cursor.endIndex); }
|
||||
while (cursor.gotoNextSibling() || cursor.gotoFirstChild());
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### tree-sitter query (S-expression)
|
||||
```scheme
|
||||
; Find all function declarations
|
||||
(function_declaration
|
||||
name: (identifier) @func.name
|
||||
parameters: (formal_parameters) @func.params)
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
; Find unused imports
|
||||
(import_statement
|
||||
source: (string) @import.source) @import
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Incremental edit
|
||||
```javascript
|
||||
const oldTree = parser.parse(oldSrc);
|
||||
const newSrc = oldSrc.slice(0, 10) + 'INSERTED' + oldSrc.slice(10);
|
||||
oldTree.edit({
|
||||
startIndex: 10, oldEndIndex: 10, newEndIndex: 18,
|
||||
startPosition: {row: 0, column: 10},
|
||||
oldEndPosition: {row: 0, column: 10},
|
||||
newEndPosition: {row: 0, column: 18},
|
||||
});
|
||||
const newTree = parser.parse(newSrc, oldTree); // reuses unchanged subtrees
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### rowan (rust-analyzer) typed wrapper
|
||||
```rust
|
||||
// Untyped GreenNode + typed SyntaxNode wrapper
|
||||
use rowan::{GreenNode, SyntaxNode};
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
#[repr(u16)]
|
||||
enum SyntaxKind { L_PAREN, R_PAREN, IDENT, FN_KW, FN_DEF, ROOT, /* ... */ }
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
struct FnDef(SyntaxNode<MyLang>);
|
||||
impl FnDef {
|
||||
fn name(&self) -> Option<String> {
|
||||
self.0.children().find(|n| n.kind() == SyntaxKind::IDENT)
|
||||
.map(|n| n.text().to_string())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Lossless rewrite (rename)
|
||||
```rust
|
||||
// Replace token in CST and reprint — preserves comments/whitespace.
|
||||
fn rename(node: &SyntaxNode, old: &str, new: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for tok in node.descendants_with_tokens() {
|
||||
if let Some(t) = tok.as_token() {
|
||||
if t.kind() == SyntaxKind::IDENT && t.text() == old { out.push_str(new); }
|
||||
else { out.push_str(t.text()); }
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Compiler / type checker | AST (semantic 충분) |
|
||||
| IDE / LSP / formatter | CST (lossless 필수) |
|
||||
| Refactoring tool | CST + typed wrapper |
|
||||
| Quick analysis script | tree-sitter query |
|
||||
| New language design | rowan or tree-sitter base |
|
||||
|
||||
**기본값**: User-facing tool 이면 매 CST. Compiler internal pass 면 매 AST.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Parser]] · [[Compiler Frontend]]
|
||||
- 변형: [[AST]] · [[GLR Parser]] · [[PEG Parser]]
|
||||
- 응용: [[tree-sitter]] · [[rust-analyzer]] · [[Roslyn]] · [[Prettier]]
|
||||
- Adjacent: [[Lexer]] · [[LSP]] · [[Incremental Parsing]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: Source-to-source transformation, IDE-grade tooling, codemods.
|
||||
**언제 X**: Pure semantic analysis (AST 만 충분).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Regex on source**: 매 fragile — CST query 사용.
|
||||
- **AST 로 formatter**: comment 손실 — CST 필수.
|
||||
- **Hand-rolled parser**: error recovery 빠짐 — tree-sitter/lark 사용.
|
||||
- **Full reparse on every keystroke**: incremental edit API 사용.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (tree-sitter docs, rust-analyzer rowan, Roslyn architecture).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — CST vs AST + tree-sitter/rowan patterns |
|
||||
|
||||
Reference in New Issue
Block a user