Skip to main content

rhwp/document_core/converters/
diagnostics.rs

1//! HWPX vs HWP IR 차이 자동 추출 도구
2//!
3//! 두 가지 모드:
4//! 1. `diff_hwpx_vs_hwp(hwpx, hwp)` — 같은 콘텐츠의 두 IR 간 영역별 차이
5//! 2. `diff_hwpx_vs_serializer_assumptions(hwpx)` — HWPX 단독 IR 이
6//!    HWP 직렬화기 가정에 위배되는 영역을 추출
7//!
8//! 본 모듈은 **읽기 전용**. IR 을 수정하지 않는다.
9
10use crate::model::control::Control;
11use crate::model::document::Document;
12
13/// 단일 IR 필드 차이 항목.
14#[derive(Debug, Clone, PartialEq)]
15pub struct IrFieldDiff {
16    /// 영역 이름 — 매핑 명세서의 항목명과 일치 (예: "table.raw_ctrl_data").
17    pub area: &'static str,
18    /// 사람이 읽을 수 있는 위치 (예: "sec=2,para=45,ctrl=0").
19    pub location: String,
20    /// HWPX 측 값 (또는 HWPX 출처 IR 의 값).
21    pub hwpx_value: String,
22    /// HWP 측 값 (또는 HWP 직렬화기 기대값).
23    pub hwp_value: String,
24}
25
26/// 영역별 카운트 요약.
27#[derive(Debug, Default, Clone)]
28pub struct DiffSummary {
29    pub items: Vec<IrFieldDiff>,
30}
31
32impl DiffSummary {
33    pub fn new() -> Self {
34        Self::default()
35    }
36
37    pub fn push(&mut self, item: IrFieldDiff) {
38        self.items.push(item);
39    }
40
41    /// 영역별 카운트.
42    pub fn counts_by_area(&self) -> Vec<(&'static str, usize)> {
43        let mut map: std::collections::BTreeMap<&'static str, usize> =
44            std::collections::BTreeMap::new();
45        for it in &self.items {
46            *map.entry(it.area).or_insert(0) += 1;
47        }
48        map.into_iter().collect()
49    }
50
51    /// 휴먼 리더블 리포트.
52    pub fn human_report(&self) -> String {
53        use std::fmt::Write;
54        let mut s = String::new();
55        let _ = writeln!(s, "[IR diff summary] total={}", self.items.len());
56        for (area, count) in self.counts_by_area() {
57            let _ = writeln!(s, "  {}: {}", area, count);
58        }
59        // 처음 20개 항목 상세
60        let _ = writeln!(s, "[details, first 20]");
61        for item in self.items.iter().take(20) {
62            let _ = writeln!(
63                s,
64                "  {} @ {}: hwpx={:?} hwp={:?}",
65                item.area, item.location, item.hwpx_value, item.hwp_value
66            );
67        }
68        s
69    }
70}
71
72/// HWPX IR 단독 검사: HWP 직렬화기 가정에 위배되는 영역을 추출한다.
73///
74/// 검사 항목 (Stage 1 베이스라인):
75/// - `table.raw_ctrl_data` 가 비어있는 표 (직렬화기가 빈 ctrl_data 작성 → 한컴 거부)
76/// - `cell.apply_inner_margin == true` 이지만 LIST_HEADER width_ref bit 0 보강 없음
77/// - `paragraph.line_segs[i].vertical_pos == 0` 인 비-첫줄 lineseg (페이지 폭주 원인)
78/// - `section.raw_stream is Some` 인지 (있으면 직렬화기 빠른 경로, 없으면 동적)
79///
80/// 본 함수는 **HWPX 출처 가정**으로 호출한다. HWP 출처에 호출해도 동작은 하지만 결과 의미는 다름.
81pub fn diff_hwpx_vs_serializer_assumptions(hwpx: &Document) -> DiffSummary {
82    let mut summary = DiffSummary::new();
83
84    for (sec_idx, section) in hwpx.sections.iter().enumerate() {
85        // section.raw_stream
86        if section.raw_stream.is_some() {
87            summary.push(IrFieldDiff {
88                area: "section.raw_stream",
89                location: format!("sec={}", sec_idx),
90                hwpx_value: "Some(...)".into(),
91                hwp_value: "(직렬화기는 raw_stream 우선 — 빠른 경로)".into(),
92            });
93        } else {
94            // None 이어도 직렬화기 동적 경로로 OK — 진단에는 기록만 하고 위반 아님
95            // (구현계획서 §1.0.2: 영역을 늘리지 않고 줄이는 것이 성공)
96        }
97
98        for (para_idx, para) in section.paragraphs.iter().enumerate() {
99            check_paragraph(sec_idx, para_idx, para, &mut summary, "");
100        }
101    }
102
103    summary
104}
105
106fn check_paragraph(
107    sec_idx: usize,
108    para_idx: usize,
109    para: &crate::model::paragraph::Paragraph,
110    summary: &mut DiffSummary,
111    path_prefix: &str,
112) {
113    // lineseg vpos == 0 (첫 줄 외)
114    for (li, ls) in para.line_segs.iter().enumerate().skip(1) {
115        if ls.vertical_pos == 0 {
116            summary.push(IrFieldDiff {
117                area: "paragraph.line_seg.vertical_pos",
118                location: format!("{}sec={},para={},ls={}", path_prefix, sec_idx, para_idx, li),
119                hwpx_value: "0".into(),
120                hwp_value: "(절대 좌표 — 직렬화기는 그대로 기록)".into(),
121            });
122        }
123    }
124
125    // 컨트롤 검사 (표 위주)
126    for (ctrl_idx, ctrl) in para.controls.iter().enumerate() {
127        if let Control::Table(t) = ctrl {
128            if t.raw_ctrl_data.is_empty() {
129                summary.push(IrFieldDiff {
130                    area: "table.raw_ctrl_data",
131                    location: format!(
132                        "{}sec={},para={},ctrl={}",
133                        path_prefix, sec_idx, para_idx, ctrl_idx
134                    ),
135                    hwpx_value: "(empty)".into(),
136                    hwp_value: "(CommonObjAttr 직렬화 필요)".into(),
137                });
138            }
139            if t.raw_table_record_attr == 0
140                && (t.attr != 0
141                    || t.repeat_header
142                    || !matches!(t.page_break, crate::model::table::TablePageBreak::None))
143            {
144                summary.push(IrFieldDiff {
145                    area: "table.raw_table_record_attr",
146                    location: format!(
147                        "{}sec={},para={},ctrl={}",
148                        path_prefix, sec_idx, para_idx, ctrl_idx
149                    ),
150                    hwpx_value: "0".into(),
151                    hwp_value: format!(
152                        "(재구성 필요: page_break={:?}, repeat={})",
153                        t.page_break, t.repeat_header
154                    ),
155                });
156            }
157            // 셀별 검사
158            for (cell_idx, cell) in t.cells.iter().enumerate() {
159                if cell.apply_inner_margin && cell.list_header_width_ref & 0x0001 == 0 {
160                    summary.push(IrFieldDiff {
161                        area: "cell.list_header_width_ref.bit0",
162                        location: format!(
163                            "{}sec={},para={},ctrl={},cell={}",
164                            path_prefix, sec_idx, para_idx, ctrl_idx, cell_idx
165                        ),
166                        hwpx_value: "apply_inner_margin=true, width_ref bit0=0".into(),
167                        hwp_value: "width_ref bit0=1 (셀 안 여백 지정)".into(),
168                    });
169                }
170                // 셀 내부 문단 재귀
171                let cell_prefix = format!(
172                    "{}cell[{},{},{},{}]/",
173                    path_prefix, sec_idx, para_idx, ctrl_idx, cell_idx
174                );
175                for (cp_idx, cpara) in cell.paragraphs.iter().enumerate() {
176                    check_paragraph(sec_idx, cp_idx, cpara, summary, &cell_prefix);
177                }
178            }
179        }
180    }
181}
182
183/// 두 IR (HWPX 출처와 HWP 출처) 의 영역별 차이를 비교한다.
184///
185/// Stage 1: 골격만 — Stage 2 이후 영역별 비교 추가.
186pub fn diff_hwpx_vs_hwp(hwpx: &Document, hwp: &Document) -> DiffSummary {
187    let mut summary = DiffSummary::new();
188
189    // 섹션 수
190    if hwpx.sections.len() != hwp.sections.len() {
191        summary.push(IrFieldDiff {
192            area: "sections.len",
193            location: "doc".into(),
194            hwpx_value: format!("{}", hwpx.sections.len()),
195            hwp_value: format!("{}", hwp.sections.len()),
196        });
197    }
198
199    // 영역별 비교는 Stage 2 부터 본격 추가.
200    // 현재 단계는 단독 검사 (diff_hwpx_vs_serializer_assumptions) 가 주력.
201    let single = diff_hwpx_vs_serializer_assumptions(hwpx);
202    for it in single.items {
203        summary.push(it);
204    }
205
206    summary
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    #[test]
214    fn empty_doc_no_diff_items_for_critical_areas() {
215        let doc = Document::default();
216        let summary = diff_hwpx_vs_serializer_assumptions(&doc);
217        // 빈 문서엔 표/lineseg 자체가 없으므로 critical 영역 차이 0
218        let counts = summary.counts_by_area();
219        assert!(
220            counts.iter().all(|(a, _)| *a != "table.raw_ctrl_data"
221                && *a != "cell.list_header_width_ref.bit0"
222                && *a != "paragraph.line_seg.vertical_pos"),
223            "empty doc should have no critical-area diffs, got: {:?}",
224            counts
225        );
226    }
227
228    #[test]
229    fn human_report_includes_total() {
230        let summary = DiffSummary::new();
231        let report = summary.human_report();
232        assert!(report.contains("total=0"));
233    }
234}