use std::collections::BTreeMap;
use std::fmt::{Debug, Write as _};
use crate::model::control::Control;
use crate::model::document::{DocInfo, Document, SectionDef};
use crate::model::paragraph::Paragraph;
use crate::model::shape::ShapeObject;
use crate::model::table::{Cell, Table};
const DEBUG_CAP: usize = 96 * 1024;
const MAX_DEPTH: usize = 14;
const VALUE_CAP: usize = 160;
pub const MAX_DIVERGENCE_EXAMPLES: usize = 2000;
pub const MAX_DIVERGENCE_PATHS: usize = 2000;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldDivergence {
pub path: String,
pub left: String,
pub right: String,
}
impl FieldDivergence {
pub fn normalized_path(&self) -> String {
normalize_path(&self.path)
}
}
fn normalize_path(path: &str) -> String {
let mut out = String::with_capacity(path.len());
let mut in_index = false;
for ch in path.chars() {
match ch {
'[' => {
in_index = true;
out.push('[');
}
']' => {
in_index = false;
out.push(']');
}
_ if in_index => {}
_ => out.push(ch),
}
}
out
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DivergenceReport {
counts: BTreeMap<String, usize>,
examples: Vec<FieldDivergence>,
}
impl DivergenceReport {
pub fn counts(&self) -> &BTreeMap<String, usize> {
&self.counts
}
pub fn examples(&self) -> &[FieldDivergence] {
&self.examples
}
pub fn total(&self) -> usize {
self.counts.values().sum()
}
pub fn is_empty(&self) -> bool {
self.counts.is_empty()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IrFieldSweepError {
Roundtrip(String),
DistinctPathLimitExceeded { limit: usize },
}
impl IrFieldSweepError {
pub fn is_capacity_error(&self) -> bool {
matches!(self, Self::DistinctPathLimitExceeded { .. })
}
}
impl std::fmt::Display for IrFieldSweepError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Roundtrip(message) => f.write_str(message),
Self::DistinctPathLimitExceeded { limit } => write!(
f,
"IR 필드 스윕 정규화 경로가 문서당 상한 {limit}종을 초과함"
),
}
}
}
impl std::error::Error for IrFieldSweepError {}
#[derive(Debug)]
struct DivergenceCollector {
counts: BTreeMap<String, usize>,
examples: Vec<FieldDivergence>,
path_limit_exceeded: bool,
}
impl DivergenceCollector {
fn new() -> Self {
Self {
counts: BTreeMap::new(),
examples: Vec::new(),
path_limit_exceeded: false,
}
}
fn record(&mut self, path: &str, left: &str, right: &str) {
if self.path_limit_exceeded {
return;
}
let normalized = normalize_path(path);
if let Some(count) = self.counts.get_mut(&normalized) {
*count += 1;
} else {
if self.counts.len() >= MAX_DIVERGENCE_PATHS {
self.path_limit_exceeded = true;
return;
}
self.counts.insert(normalized, 1);
}
if self.examples.len() < MAX_DIVERGENCE_EXAMPLES {
self.examples.push(FieldDivergence {
path: path.to_string(),
left: truncate(left),
right: truncate(right),
});
}
}
fn is_failed(&self) -> bool {
self.path_limit_exceeded
}
fn finish(self) -> Result<DivergenceReport, IrFieldSweepError> {
if self.path_limit_exceeded {
return Err(IrFieldSweepError::DistinctPathLimitExceeded {
limit: MAX_DIVERGENCE_PATHS,
});
}
Ok(DivergenceReport {
counts: self.counts,
examples: self.examples,
})
}
}
impl std::fmt::Display for FieldDivergence {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {} → {}", self.path, self.left, self.right)
}
}
struct CappedWriter {
buf: String,
cap: usize,
overflow: bool,
}
impl std::fmt::Write for CappedWriter {
fn write_str(&mut self, s: &str) -> std::fmt::Result {
if self.buf.len() + s.len() > self.cap {
self.overflow = true;
return Err(std::fmt::Error);
}
self.buf.push_str(s);
Ok(())
}
}
fn debug_capped<T: Debug + ?Sized>(v: &T) -> (String, bool) {
let mut w = CappedWriter {
buf: String::new(),
cap: DEBUG_CAP,
overflow: false,
};
let _ = write!(w, "{v:?}");
(w.buf, w.overflow)
}
fn split_top_level(body: &str) -> Option<Vec<&str>> {
let mut parts = Vec::new();
let mut depth = 0i32;
let mut start = 0usize;
let mut quote: Option<u8> = None;
let b = body.as_bytes();
let mut i = 0usize;
while i < b.len() {
let c = b[i];
if let Some(q) = quote {
if c == b'\\' {
i += 2;
continue;
}
if c == q {
quote = None;
}
i += 1;
continue;
}
match c {
b'"' | b'\'' => quote = Some(c),
b'{' | b'[' | b'(' => depth += 1,
b'}' | b']' | b')' => {
depth -= 1;
if depth < 0 {
return None;
}
}
b',' if depth == 0 => {
parts.push(&body[start..i]);
start = i + 1;
}
_ => {}
}
i += 1;
}
if depth != 0 || quote.is_some() {
return None;
}
parts.push(&body[start..]);
Some(parts)
}
fn split_field(part: &str) -> Option<(&str, &str)> {
let mut depth = 0i32;
let mut quote: Option<u8> = None;
let b = part.as_bytes();
let mut i = 0usize;
while i < b.len() {
let c = b[i];
if let Some(q) = quote {
if c == b'\\' {
i += 2;
continue;
}
if c == q {
quote = None;
}
i += 1;
continue;
}
match c {
b'"' | b'\'' => quote = Some(c),
b'{' | b'[' | b'(' => depth += 1,
b'}' | b']' | b')' => depth -= 1,
b':' if depth == 0 => return Some((&part[..i], &part[i + 1..])),
_ => {}
}
i += 1;
}
None
}
fn split_debug(s: &str) -> Option<(&str, Vec<(&str, &str)>)> {
let s = s.trim();
if s.len() < 2 || s.starts_with('"') {
return None;
}
let open_idx = s.find(['{', '[', '('])?;
let open = s.as_bytes()[open_idx];
let close = match open {
b'{' => '}',
b'[' => ']',
_ => ')',
};
if !s.ends_with(close) {
return None;
}
let head = s[..open_idx].trim();
let body = &s[open_idx + 1..s.len() - 1];
let parts = split_top_level(body)?;
let named = open == b'{';
let mut out = Vec::with_capacity(parts.len());
for (i, part) in parts.iter().enumerate() {
let part = part.trim();
if part.is_empty() {
continue;
}
if named {
let (k, v) = split_field(part)?;
out.push((k.trim(), v.trim()));
} else {
let key = INDEX_KEYS.get(i).copied().unwrap_or("n");
out.push((key, part));
}
}
Some((head, out))
}
const INDEX_KEYS: &[&str] = &[
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16",
"17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31",
];
fn unwrap_some<'a>(a: &'a str, b: &'a str) -> (&'a str, &'a str) {
let peel = |s: &'a str| -> Option<&'a str> {
let s = s.trim();
if s.starts_with("Some(") && s.ends_with(')') {
Some(s["Some(".len()..s.len() - 1].trim())
} else {
None
}
};
match (peel(a), peel(b)) {
(Some(x), Some(y)) => (x, y),
_ => (a, b),
}
}
fn truncate(s: &str) -> String {
if s.chars().count() <= VALUE_CAP {
return s.to_string();
}
let cut: String = s.chars().take(VALUE_CAP).collect();
format!("{cut}…")
}
fn push_leaf(path: &str, a: &str, b: &str, out: &mut DivergenceCollector) {
out.record(path, a, b);
}
fn compare_node(path: &str, a: &str, b: &str, depth: usize, out: &mut DivergenceCollector) {
if a == b || out.is_failed() {
return;
}
if depth >= MAX_DEPTH {
push_leaf(path, a, b, out);
return;
}
let (a, b) = unwrap_some(a, b);
if a == b {
return;
}
let (Some((head_a, kids_a)), Some((head_b, kids_b))) = (split_debug(a), split_debug(b)) else {
push_leaf(path, a, b, out);
return;
};
if head_a != head_b {
push_leaf(path, a, b, out);
return;
}
if kids_a.len() != kids_b.len() {
push_leaf(
&format!("{path}.len"),
&kids_a.len().to_string(),
&kids_b.len().to_string(),
out,
);
}
for (idx, ((ka, va), (kb, vb))) in kids_a.iter().zip(kids_b.iter()).enumerate() {
if ka != kb {
push_leaf(path, a, b, out);
return;
}
let child = if ka.as_bytes().first().is_some_and(|c| c.is_ascii_digit()) {
format!("{path}[{idx}]")
} else {
format!("{path}.{ka}")
};
compare_node(&child, va, vb, depth + 1, out);
}
}
fn cmp_debug<T: Debug + ?Sized>(path: &str, a: &T, b: &T, out: &mut DivergenceCollector) {
if out.is_failed() {
return;
}
let (sa, _) = debug_capped(a);
let (sb, _) = debug_capped(b);
compare_node(path, &sa, &sb, 0, out);
}
fn cmp_count(path: &str, a: usize, b: usize, out: &mut DivergenceCollector) {
if a != b {
push_leaf(&format!("{path}.len"), &a.to_string(), &b.to_string(), out);
}
}
pub fn sweep_documents(a: &Document, b: &Document) -> Result<DivergenceReport, IrFieldSweepError> {
let mut out = DivergenceCollector::new();
sweep_doc_info(&a.doc_info, &b.doc_info, &mut out);
cmp_count("sections", a.sections.len(), b.sections.len(), &mut out);
for (i, (sa, sb)) in a.sections.iter().zip(b.sections.iter()).enumerate() {
if out.is_failed() {
break;
}
let base = format!("sections[{i}]");
sweep_section_def(&base, &sa.section_def, &sb.section_def, &mut out);
sweep_paragraphs(
&format!("{base}.paragraphs"),
&sa.paragraphs,
&sb.paragraphs,
&mut out,
);
}
out.finish()
}
fn sweep_doc_info(a: &DocInfo, b: &DocInfo, out: &mut DivergenceCollector) {
macro_rules! table {
($f:ident) => {{
let base = concat!("doc_info.", stringify!($f));
cmp_count(base, a.$f.len(), b.$f.len(), out);
for (i, (x, y)) in a.$f.iter().zip(b.$f.iter()).enumerate() {
cmp_debug(&format!("{base}[{i}]"), x, y, out);
}
}};
}
table!(char_shapes);
table!(para_shapes);
table!(border_fills);
table!(tab_defs);
table!(numberings);
table!(bullets);
table!(styles);
table!(bin_data_list);
cmp_count(
"doc_info.font_faces",
a.font_faces.len(),
b.font_faces.len(),
out,
);
for (i, (xs, ys)) in a.font_faces.iter().zip(b.font_faces.iter()).enumerate() {
let base = format!("doc_info.font_faces[{i}]");
cmp_count(&base, xs.len(), ys.len(), out);
for (j, (x, y)) in xs.iter().zip(ys.iter()).enumerate() {
cmp_debug(&format!("{base}[{j}]"), x, y, out);
}
}
cmp_debug(
"doc_info.bullet_count",
&a.bullet_count,
&b.bullet_count,
out,
);
cmp_debug(
"doc_info.memo_shape_count",
&a.memo_shape_count,
&b.memo_shape_count,
out,
);
cmp_debug(
"doc_info.hwpml_version",
&a.hwpml_version,
&b.hwpml_version,
out,
);
cmp_count(
"doc_info.extra_records",
a.extra_records.len(),
b.extra_records.len(),
out,
);
}
fn sweep_section_def(base: &str, a: &SectionDef, b: &SectionDef, out: &mut DivergenceCollector) {
cmp_count(
&format!("{base}.section_def.extra_child_records"),
a.extra_child_records.len(),
b.extra_child_records.len(),
out,
);
cmp_count(
&format!("{base}.section_def.master_pages"),
a.master_pages.len(),
b.master_pages.len(),
out,
);
let mut sa = a.clone();
let mut sb = b.clone();
sa.extra_child_records.clear();
sa.master_pages.clear();
sb.extra_child_records.clear();
sb.master_pages.clear();
cmp_debug(&format!("{base}.section_def"), &sa, &sb, out);
}
fn sweep_paragraphs(base: &str, a: &[Paragraph], b: &[Paragraph], out: &mut DivergenceCollector) {
cmp_count(base, a.len(), b.len(), out);
for (i, (pa, pb)) in a.iter().zip(b.iter()).enumerate() {
if out.is_failed() {
return;
}
sweep_paragraph(&format!("{base}[{i}]"), pa, pb, out);
}
}
fn sweep_paragraph(base: &str, a: &Paragraph, b: &Paragraph, out: &mut DivergenceCollector) {
let Paragraph {
char_count,
control_mask,
para_shape_id,
style_id,
column_type,
raw_break_type,
page_break_synthesized: _,
source_line_seg_vertical_pos: _,
layout_rebased_body_axis: _,
hwpx_axis_shift: _,
text,
char_offsets,
literal_figure_spaces,
nb_space_control_indices,
char_shapes,
line_segs,
range_tags,
field_ranges,
orphan_field_ends,
controls,
ctrl_data_records,
char_count_msb,
raw_header_extra,
has_para_text,
tab_extended,
title_marks,
markpen_marks,
numbering_restart,
stored_text_partition_dirty: _,
layout_only_fill_lines: _,
cell_format_vpos_dirty: _,
cell_vpos_reset: _,
stored_flow_shifted: _,
layout_space_metrics: _,
hwp3_saved_space_corrections: _,
layout_object_projection: _,
layout_float_band: _,
layout_cell_grid: _,
layout_field_values: _,
numbering_marker: _,
} = a;
macro_rules! f {
($n:ident) => {
cmp_debug(&format!("{base}.{}", stringify!($n)), $n, &b.$n, out)
};
}
f!(char_count);
f!(control_mask);
f!(para_shape_id);
f!(style_id);
f!(column_type);
f!(raw_break_type);
f!(text);
f!(char_offsets);
f!(literal_figure_spaces);
if nb_space_control_indices.is_some() && b.nb_space_control_indices.is_some() {
f!(nb_space_control_indices);
}
f!(char_shapes);
f!(line_segs);
f!(range_tags);
f!(field_ranges);
f!(orphan_field_ends);
f!(ctrl_data_records);
f!(char_count_msb);
f!(raw_header_extra);
f!(has_para_text);
f!(tab_extended);
f!(title_marks);
f!(markpen_marks);
f!(numbering_restart);
sweep_controls(&format!("{base}.controls"), controls, &b.controls, out);
}
fn sweep_controls(base: &str, a: &[Control], b: &[Control], out: &mut DivergenceCollector) {
cmp_count(base, a.len(), b.len(), out);
for (i, (ca, cb)) in a.iter().zip(b.iter()).enumerate() {
if out.is_failed() {
return;
}
sweep_control(&format!("{base}[{i}]"), ca, cb, out);
}
}
fn sweep_control(base: &str, a: &Control, b: &Control, out: &mut DivergenceCollector) {
use Control::*;
match (a, b) {
(Table(ta), Table(tb)) => sweep_table(base, ta, tb, out),
(Header(ha), Header(hb)) => {
let (mut x, mut y) = (ha.clone(), hb.clone());
x.paragraphs.clear();
y.paragraphs.clear();
cmp_debug(base, &x, &y, out);
sweep_paragraphs(
&format!("{base}.paragraphs"),
&ha.paragraphs,
&hb.paragraphs,
out,
);
}
(Footer(ha), Footer(hb)) => {
let (mut x, mut y) = (ha.clone(), hb.clone());
x.paragraphs.clear();
y.paragraphs.clear();
cmp_debug(base, &x, &y, out);
sweep_paragraphs(
&format!("{base}.paragraphs"),
&ha.paragraphs,
&hb.paragraphs,
out,
);
}
(Footnote(fa), Footnote(fb)) => {
let (mut x, mut y) = (fa.clone(), fb.clone());
x.paragraphs.clear();
y.paragraphs.clear();
cmp_debug(base, &x, &y, out);
sweep_paragraphs(
&format!("{base}.paragraphs"),
&fa.paragraphs,
&fb.paragraphs,
out,
);
}
(Endnote(fa), Endnote(fb)) => {
let (mut x, mut y) = (fa.clone(), fb.clone());
x.paragraphs.clear();
y.paragraphs.clear();
cmp_debug(base, &x, &y, out);
sweep_paragraphs(
&format!("{base}.paragraphs"),
&fa.paragraphs,
&fb.paragraphs,
out,
);
}
(Field(fa), Field(fb)) => {
let (mut x, mut y) = (fa.clone(), fb.clone());
x.memo_paragraphs.clear();
y.memo_paragraphs.clear();
cmp_debug(base, &x, &y, out);
sweep_paragraphs(
&format!("{base}.memo_paragraphs"),
&fa.memo_paragraphs,
&fb.memo_paragraphs,
out,
);
}
(Picture(pa), Picture(pb)) => {
let (mut x, mut y) = (pa.clone(), pb.clone());
if let Some(c) = x.caption.as_mut() {
c.paragraphs.clear();
}
if let Some(c) = y.caption.as_mut() {
c.paragraphs.clear();
}
cmp_debug(base, &x, &y, out);
sweep_caption_paragraphs(base, &pa.caption, &pb.caption, out);
}
(Shape(sa), Shape(sb)) => sweep_shape(base, sa, sb, out),
(Form(fa), Form(fb)) => sweep_form(base, fa, fb, out),
(HiddenComment(ha), HiddenComment(hb)) => sweep_paragraphs(
&format!("{base}.paragraphs"),
&ha.paragraphs,
&hb.paragraphs,
out,
),
(SectionDef(x), SectionDef(y)) => sweep_section_def(base, x, y, out),
(ColumnDef(x), ColumnDef(y)) => cmp_debug(base, x, y, out),
(AutoNumber(x), AutoNumber(y)) => cmp_debug(base, x, y, out),
(NewNumber(x), NewNumber(y)) => cmp_debug(base, x, y, out),
(PageNumberPos(x), PageNumberPos(y)) => cmp_debug(base, x, y, out),
(Bookmark(x), Bookmark(y)) => cmp_debug(base, x, y, out),
(Hyperlink(x), Hyperlink(y)) => cmp_debug(base, x, y, out),
(Ruby(x), Ruby(y)) => cmp_debug(base, x, y, out),
(CharOverlap(x), CharOverlap(y)) => cmp_debug(base, x, y, out),
(PageHide(x), PageHide(y)) => cmp_debug(base, x, y, out),
(Equation(x), Equation(y)) => cmp_debug(base, x, y, out),
(IndexMark(x), IndexMark(y)) => cmp_debug(base, x, y, out),
(PageNumCtrl(x), PageNumCtrl(y)) => cmp_debug(base, x, y, out),
(Unknown(x), Unknown(y)) => cmp_debug(base, x, y, out),
_ => push_leaf(base, control_kind(a), control_kind(b), out),
}
}
fn control_kind(c: &Control) -> &'static str {
use Control::*;
match c {
SectionDef(_) => "SectionDef",
ColumnDef(_) => "ColumnDef",
Table(_) => "Table",
Shape(_) => "Shape",
Picture(_) => "Picture",
Header(_) => "Header",
Footer(_) => "Footer",
Footnote(_) => "Footnote",
Endnote(_) => "Endnote",
AutoNumber(_) => "AutoNumber",
NewNumber(_) => "NewNumber",
PageNumberPos(_) => "PageNumberPos",
Bookmark(_) => "Bookmark",
IndexMark(_) => "IndexMark",
PageNumCtrl(_) => "PageNumCtrl",
Hyperlink(_) => "Hyperlink",
Ruby(_) => "Ruby",
CharOverlap(_) => "CharOverlap",
PageHide(_) => "PageHide",
HiddenComment(_) => "HiddenComment",
Equation(_) => "Equation",
Field(_) => "Field",
Form(_) => "Form",
Unknown(_) => "Unknown",
}
}
fn sweep_form(
base: &str,
a: &crate::model::control::FormObject,
b: &crate::model::control::FormObject,
out: &mut DivergenceCollector,
) {
let crate::model::control::FormObject {
common,
form_type,
name,
caption,
text,
width,
height,
fore_color,
back_color,
value,
enabled,
properties,
} = a;
macro_rules! f {
($n:ident) => {
cmp_debug(&format!("{base}.{}", stringify!($n)), $n, &b.$n, out)
};
}
f!(common);
f!(form_type);
f!(name);
f!(caption);
f!(text);
f!(width);
f!(height);
f!(fore_color);
f!(back_color);
f!(value);
f!(enabled);
let sorted = |m: &std::collections::HashMap<String, String>| {
m.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect::<std::collections::BTreeMap<_, _>>()
};
cmp_debug(
&format!("{base}.properties"),
&sorted(properties),
&sorted(&b.properties),
out,
);
}
fn sweep_caption_paragraphs(
base: &str,
a: &Option<crate::model::shape::Caption>,
b: &Option<crate::model::shape::Caption>,
out: &mut DivergenceCollector,
) {
if let (Some(x), Some(y)) = (a, b) {
sweep_paragraphs(
&format!("{base}.caption.paragraphs"),
&x.paragraphs,
&y.paragraphs,
out,
);
}
}
fn sweep_table(base: &str, a: &Table, b: &Table, out: &mut DivergenceCollector) {
let Table {
attr,
row_count,
col_count,
cell_spacing,
padding,
row_sizes,
border_fill_id,
zones,
cells,
cell_grid,
page_break,
repeat_header,
caption,
common,
outer_margin_left,
outer_margin_right,
outer_margin_top,
outer_margin_bottom,
raw_ctrl_data,
raw_ctrl_seal: _,
raw_table_record_attr,
raw_table_record_extra,
layout_page_break_cache: _,
} = a;
macro_rules! f {
($n:ident) => {
cmp_debug(&format!("{base}.{}", stringify!($n)), $n, &b.$n, out)
};
}
f!(attr);
f!(row_count);
f!(col_count);
f!(cell_spacing);
f!(padding);
f!(row_sizes);
f!(border_fill_id);
f!(zones);
f!(cell_grid);
f!(page_break);
f!(repeat_header);
f!(common);
f!(outer_margin_left);
f!(outer_margin_right);
f!(outer_margin_top);
f!(outer_margin_bottom);
f!(raw_ctrl_data);
f!(raw_table_record_attr);
f!(raw_table_record_extra);
{
let strip = |c: &Option<crate::model::shape::Caption>| {
c.clone().map(|mut v| {
v.paragraphs.clear();
v
})
};
cmp_debug(
&format!("{base}.caption"),
&strip(caption),
&strip(&b.caption),
out,
);
sweep_caption_paragraphs(base, caption, &b.caption, out);
}
let cells_path = format!("{base}.cells");
cmp_count(&cells_path, cells.len(), b.cells.len(), out);
for (i, (ca, cb)) in cells.iter().zip(b.cells.iter()).enumerate() {
if out.is_failed() {
return;
}
sweep_cell(&format!("{cells_path}[{i}]"), ca, cb, out);
}
}
fn sweep_cell(base: &str, a: &Cell, b: &Cell, out: &mut DivergenceCollector) {
let Cell {
col,
row,
col_span,
row_span,
width,
height,
padding,
border_fill_id,
paragraphs,
list_header_width_ref,
text_direction,
line_wrap,
vertical_align,
apply_inner_margin,
is_header,
raw_list_extra,
field_name,
dirty_flag,
} = a;
macro_rules! f {
($n:ident) => {
cmp_debug(&format!("{base}.{}", stringify!($n)), $n, &b.$n, out)
};
}
f!(col);
f!(row);
f!(col_span);
f!(row_span);
f!(width);
f!(height);
f!(padding);
f!(border_fill_id);
f!(list_header_width_ref);
f!(text_direction);
f!(line_wrap);
f!(vertical_align);
f!(apply_inner_margin);
f!(is_header);
f!(raw_list_extra);
f!(field_name);
f!(dirty_flag);
sweep_paragraphs(
&format!("{base}.paragraphs"),
paragraphs,
&b.paragraphs,
out,
);
}
fn sweep_shape(base: &str, a: &ShapeObject, b: &ShapeObject, out: &mut DivergenceCollector) {
let mut x = a.clone();
let mut y = b.clone();
strip_shape(&mut x);
strip_shape(&mut y);
cmp_debug(base, &x, &y, out);
if let (Some(ta), Some(tb)) = (shape_text_box(a), shape_text_box(b)) {
sweep_paragraphs(
&format!("{base}.text_box.paragraphs"),
&ta.paragraphs,
&tb.paragraphs,
out,
);
}
sweep_caption_paragraphs(base, shape_caption(a), shape_caption(b), out);
if let (ShapeObject::Group(ga), ShapeObject::Group(gb)) = (a, b) {
let path = format!("{base}.children");
cmp_count(&path, ga.children.len(), gb.children.len(), out);
for (i, (ca, cb)) in ga.children.iter().zip(gb.children.iter()).enumerate() {
if out.is_failed() {
return;
}
sweep_shape(&format!("{path}[{i}]"), ca, cb, out);
}
}
}
fn strip_shape(s: &mut ShapeObject) {
use ShapeObject::*;
macro_rules! drawing {
($x:expr) => {{
if let Some(tb) = $x.drawing.text_box.as_mut() {
tb.paragraphs.clear();
}
if let Some(c) = $x.drawing.caption.as_mut() {
c.paragraphs.clear();
}
}};
}
match s {
Line(x) => drawing!(x),
Rectangle(x) => drawing!(x),
Ellipse(x) => drawing!(x),
Arc(x) => drawing!(x),
Polygon(x) => drawing!(x),
Curve(x) => drawing!(x),
Chart(x) => {
drawing!(x);
if let Some(c) = x.caption.as_mut() {
c.paragraphs.clear();
}
}
Ole(x) => {
drawing!(x);
if let Some(c) = x.caption.as_mut() {
c.paragraphs.clear();
}
}
Group(x) => {
if let Some(c) = x.caption.as_mut() {
c.paragraphs.clear();
}
x.children.clear();
}
Picture(x) => {
if let Some(c) = x.caption.as_mut() {
c.paragraphs.clear();
}
}
}
}
fn shape_text_box(s: &ShapeObject) -> Option<&crate::model::shape::TextBox> {
use ShapeObject::*;
match s {
Line(x) => x.drawing.text_box.as_ref(),
Rectangle(x) => x.drawing.text_box.as_ref(),
Ellipse(x) => x.drawing.text_box.as_ref(),
Arc(x) => x.drawing.text_box.as_ref(),
Polygon(x) => x.drawing.text_box.as_ref(),
Curve(x) => x.drawing.text_box.as_ref(),
Chart(x) => x.drawing.text_box.as_ref(),
Ole(x) => x.drawing.text_box.as_ref(),
Group(_) | Picture(_) => None,
}
}
fn shape_caption(s: &ShapeObject) -> &Option<crate::model::shape::Caption> {
use ShapeObject::*;
match s {
Line(x) => &x.drawing.caption,
Rectangle(x) => &x.drawing.caption,
Ellipse(x) => &x.drawing.caption,
Arc(x) => &x.drawing.caption,
Polygon(x) => &x.drawing.caption,
Curve(x) => &x.drawing.caption,
Chart(x) => &x.caption,
Ole(x) => &x.caption,
Group(x) => &x.caption,
Picture(x) => &x.caption,
}
}
pub fn sweep_hwp5_roundtrip(bytes: &[u8]) -> Result<DivergenceReport, IrFieldSweepError> {
use crate::parser::parse_document;
use crate::serializer::serialize_document;
let doc1 = parse_document(bytes)
.map_err(|e| IrFieldSweepError::Roundtrip(format!("파싱 실패: {e}")))?;
let out = serialize_document(&doc1)
.map_err(|e| IrFieldSweepError::Roundtrip(format!("직렬화 실패: {e}")))?;
let doc2 = parse_document(&out)
.map_err(|e| IrFieldSweepError::Roundtrip(format!("재파싱 실패: {e}")))?;
sweep_documents(&doc1, &doc2)
}
pub fn sweep_hwp5_rebuild_roundtrip(bytes: &[u8]) -> Result<DivergenceReport, IrFieldSweepError> {
use crate::parser::parse_document;
use crate::serializer::serialize_document;
let doc1 = parse_document(bytes)
.map_err(|e| IrFieldSweepError::Roundtrip(format!("파싱 실패: {e}")))?;
let mut edited = doc1.clone();
edited.doc_info.raw_stream_dirty = true;
for s in &mut edited.sections {
s.raw_stream = None;
}
let out = serialize_document(&edited)
.map_err(|e| IrFieldSweepError::Roundtrip(format!("직렬화 실패: {e}")))?;
let doc2 = parse_document(&out)
.map_err(|e| IrFieldSweepError::Roundtrip(format!("재파싱 실패: {e}")))?;
sweep_documents(&doc1, &doc2)
}
pub fn sweep_hwpx_roundtrip(bytes: &[u8]) -> Result<DivergenceReport, IrFieldSweepError> {
use crate::parser::hwpx::parse_hwpx;
use crate::serializer::hwpx::serialize_hwpx;
let doc1 =
parse_hwpx(bytes).map_err(|e| IrFieldSweepError::Roundtrip(format!("파싱 실패: {e}")))?;
let out = serialize_hwpx(&doc1)
.map_err(|e| IrFieldSweepError::Roundtrip(format!("직렬화 실패: {e}")))?;
let doc2 =
parse_hwpx(&out).map_err(|e| IrFieldSweepError::Roundtrip(format!("재파싱 실패: {e}")))?;
sweep_documents(&doc1, &doc2)
}
pub fn tally(report: &DivergenceReport) -> &BTreeMap<String, usize> {
report.counts()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn split_debug_struct() {
let (head, kids) = split_debug("CharShape { bold: true, size: 1000 }").unwrap();
assert_eq!(head, "CharShape");
assert_eq!(kids, vec![("bold", "true"), ("size", "1000")]);
}
#[test]
fn split_debug_seq() {
let (head, kids) = split_debug("[1, 2, 3]").unwrap();
assert_eq!(head, "");
assert_eq!(kids, vec![("0", "1"), ("1", "2"), ("2", "3")]);
}
#[test]
fn split_debug_nested_commas_are_not_split() {
let (_, kids) = split_debug("T { a: [1, 2], b: S { c: 3 } }").unwrap();
assert_eq!(kids, vec![("a", "[1, 2]"), ("b", "S { c: 3 }")]);
}
#[test]
fn split_debug_string_with_comma_and_braces() {
let (_, kids) = split_debug(r#"T { name: "a, b { c", n: 1 }"#).unwrap();
assert_eq!(kids, vec![("name", r#""a, b { c""#), ("n", "1")]);
}
#[test]
fn split_debug_rejects_scalar() {
assert!(split_debug("42").is_none());
assert!(split_debug("true").is_none());
assert!(split_debug(r#""hello""#).is_none());
assert!(split_debug("None").is_none());
}
#[test]
fn compare_node_reports_leaf_path() {
let mut out = DivergenceCollector::new();
compare_node(
"t",
"T { a: 1, b: S { c: 2 } }",
"T { a: 1, b: S { c: 9 } }",
0,
&mut out,
);
let report = out.finish().unwrap();
assert_eq!(report.total(), 1);
assert_eq!(report.examples()[0].path, "t.b.c");
assert_eq!(report.examples()[0].left, "2");
assert_eq!(report.examples()[0].right, "9");
}
#[test]
fn compare_node_reports_seq_length_and_common_prefix() {
let mut out = DivergenceCollector::new();
compare_node("v", "[1, 2, 3]", "[1, 9]", 0, &mut out);
let report = out.finish().unwrap();
let paths: Vec<&str> = report.examples().iter().map(|d| d.path.as_str()).collect();
assert!(paths.contains(&"v.len"), "길이 발산 누락: {paths:?}");
assert!(paths.contains(&"v[1]"), "값 발산 누락: {paths:?}");
}
#[test]
fn compare_node_unwraps_matching_some() {
let mut out = DivergenceCollector::new();
compare_node("c", "Some(S { x: 1 })", "Some(S { x: 2 })", 0, &mut out);
let report = out.finish().unwrap();
assert_eq!(report.total(), 1);
assert_eq!(
report.examples()[0].path,
"c.x",
"Some 은 경로에 투명해야 함"
);
}
#[test]
fn compare_node_some_vs_none_is_leaf() {
let mut out = DivergenceCollector::new();
compare_node("c", "Some(S { x: 1 })", "None", 0, &mut out);
let report = out.finish().unwrap();
assert_eq!(report.total(), 1);
assert_eq!(report.examples()[0].path, "c");
assert_eq!(report.examples()[0].right, "None");
}
#[test]
fn compare_node_different_variant_is_leaf() {
let mut out = DivergenceCollector::new();
compare_node("s", "Line { a: 1 }", "Rectangle { a: 1 }", 0, &mut out);
let report = out.finish().unwrap();
assert_eq!(report.total(), 1);
assert_eq!(report.examples()[0].path, "s");
}
#[test]
fn identical_values_produce_nothing() {
let mut out = DivergenceCollector::new();
compare_node("x", "T { a: 1 }", "T { a: 1 }", 0, &mut out);
assert!(out.finish().unwrap().is_empty());
}
#[test]
fn normalized_path_strips_indices() {
let d = FieldDivergence {
path: "sections[0].paragraphs[37].controls[1].common.z_order".to_string(),
left: "1".into(),
right: "2".into(),
};
assert_eq!(
d.normalized_path(),
"sections[].paragraphs[].controls[].common.z_order"
);
}
#[test]
fn capped_writer_truncates_large_debug() {
let big: Vec<u32> = (0..200_000).collect();
let (s, overflow) = debug_capped(&big);
assert!(overflow, "상한 초과가 감지되어야 함");
assert!(s.len() <= DEBUG_CAP, "상한을 넘겨 문자열화하면 안 됨");
}
#[test]
fn debug_capped_small_value_is_complete() {
let (s, overflow) = debug_capped(&(1u8, 2u8));
assert!(!overflow);
assert_eq!(s, "(1, 2)");
}
#[test]
fn tally_groups_by_normalized_path() {
let mut collector = DivergenceCollector::new();
collector.record("sections[0].paragraphs[1].text", "a", "b");
collector.record("sections[0].paragraphs[9].text", "a", "b");
let report = collector.finish().unwrap();
let t = tally(&report);
assert_eq!(t.get("sections[].paragraphs[].text"), Some(&2));
}
#[test]
fn distinct_path_limit_fails_closed() {
let mut collector = DivergenceCollector::new();
for index in 0..MAX_DIVERGENCE_PATHS {
collector.record(&format!("field_{index}"), "left", "right");
}
collector.record("one_path_too_many", "left", "right");
assert_eq!(
collector.finish(),
Err(IrFieldSweepError::DistinctPathLimitExceeded {
limit: MAX_DIVERGENCE_PATHS
})
);
}
#[test]
fn sweep_detects_single_table_attribute_change() {
use crate::model::control::Control;
use crate::model::document::{Document, Section};
use crate::model::paragraph::Paragraph;
use crate::model::table::Table;
let mut tbl = Table::default();
tbl.row_count = 2;
let mut para = Paragraph::default();
para.controls.push(Control::Table(Box::new(tbl)));
let mut doc_a = Document::default();
doc_a.sections.push(Section {
paragraphs: vec![para],
..Default::default()
});
let mut doc_b = doc_a.clone();
if let Control::Table(t) = &mut doc_b.sections[0].paragraphs[0].controls[0] {
t.row_count = 3;
}
let report = sweep_documents(&doc_a, &doc_b).unwrap();
let divs = report.examples();
assert_eq!(report.total(), 1, "예상 밖 발산: {report:?}");
assert_eq!(
divs[0].path,
"sections[0].paragraphs[0].controls[0].row_count"
);
assert_eq!(divs[0].left, "2");
assert_eq!(divs[0].right, "3");
}
#[test]
fn sweep_identical_documents_is_empty() {
use crate::model::document::{Document, Section};
use crate::model::paragraph::Paragraph;
let mut doc = Document::default();
doc.sections.push(Section {
paragraphs: vec![Paragraph {
text: "가나다".to_string(),
..Default::default()
}],
..Default::default()
});
let copy = doc.clone();
assert!(sweep_documents(&doc, ©).unwrap().is_empty());
}
}