use std::fmt;
use crate::model::control::Control;
use crate::model::document::Section;
use crate::model::paragraph::Paragraph;
use crate::model::table::Cell;
use super::ast::{Axis, AxisKind};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum NodeStep {
Section(u32),
Para(u32),
Control(u32),
Cell(u32),
Run(u32),
}
impl NodeStep {
pub const fn axis_name(self) -> &'static str {
match self {
NodeStep::Section(_) => "section",
NodeStep::Para(_) => "para",
NodeStep::Control(_) => "control",
NodeStep::Cell(_) => "cell",
NodeStep::Run(_) => "run",
}
}
pub const fn kind_ord(self) -> u8 {
match self {
NodeStep::Section(_) => 0,
NodeStep::Para(_) => 1,
NodeStep::Control(_) => 2,
NodeStep::Cell(_) => 3,
NodeStep::Run(_) => 4,
}
}
pub const fn index(self) -> u32 {
match self {
NodeStep::Section(i)
| NodeStep::Para(i)
| NodeStep::Control(i)
| NodeStep::Cell(i)
| NodeStep::Run(i) => i,
}
}
}
impl fmt::Display for NodeStep {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "/{}[{}]", self.axis_name(), self.index())
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NodeId {
steps: Vec<NodeStep>,
}
impl NodeId {
pub fn root() -> NodeId {
NodeId { steps: Vec::new() }
}
pub fn child(&self, step: NodeStep) -> NodeId {
let mut steps = self.steps.clone();
steps.push(step);
NodeId { steps }
}
pub fn steps(&self) -> &[NodeStep] {
&self.steps
}
pub fn depth(&self) -> usize {
self.steps.len()
}
pub fn parent(&self) -> Option<NodeId> {
if self.steps.is_empty() {
return None;
}
Some(NodeId {
steps: self.steps[..self.steps.len() - 1].to_vec(),
})
}
pub fn is_descendant_of(&self, other: &NodeId) -> bool {
self.steps.len() > other.steps.len() && self.steps.starts_with(&other.steps)
}
pub fn is_sibling_of(&self, other: &NodeId) -> bool {
self.steps.len() == other.steps.len()
&& !self.steps.is_empty()
&& self.steps[..self.steps.len() - 1] == other.steps[..other.steps.len() - 1]
}
}
impl fmt::Display for NodeId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.steps.is_empty() {
return f.write_str("/");
}
for step in &self.steps {
write!(f, "{step}")?;
}
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
pub struct RunView<'d> {
para: &'d Paragraph,
byte_start: usize,
byte_end: usize,
char_shape_id: u32,
}
impl<'d> RunView<'d> {
pub fn text(&self) -> &'d str {
&self.para.text[self.byte_start..self.byte_end]
}
pub const fn char_shape_id(&self) -> u32 {
self.char_shape_id
}
pub const fn paragraph(&self) -> &'d Paragraph {
self.para
}
}
pub fn runs_of(para: &Paragraph) -> Vec<RunView<'_>> {
if para.char_shapes.is_empty() || para.text.is_empty() {
return Vec::new();
}
let mut byte_at: Vec<usize> = para.text.char_indices().map(|(b, _)| b).collect();
byte_at.push(para.text.len());
let char_count = byte_at.len() - 1;
let to_char_index = |utf16_pos: u32| -> usize {
if para.char_offsets.len() == char_count {
para.char_offsets.partition_point(|&o| o < utf16_pos)
} else {
(utf16_pos as usize).min(char_count)
}
};
let mut starts: Vec<usize> = para
.char_shapes
.iter()
.map(|cs| to_char_index(cs.start_pos).min(char_count))
.collect();
starts[0] = 0;
let mut runs = Vec::with_capacity(starts.len());
for (i, &start) in starts.iter().enumerate() {
let end = starts.get(i + 1).copied().unwrap_or(char_count);
if end <= start {
continue;
}
runs.push(RunView {
para,
byte_start: byte_at[start],
byte_end: byte_at[end],
char_shape_id: para.char_shapes[i].char_shape_id,
});
}
runs
}
#[derive(Debug, Clone, Copy)]
pub enum Node<'d> {
Section(&'d Section),
Para(&'d Paragraph),
Run(RunView<'d>),
Control(&'d Control),
Cell(&'d Cell),
}
impl<'d> Node<'d> {
pub fn matches_axis(&self, axis: Axis) -> bool {
let kind = match axis {
Axis::Any => return true,
Axis::Kind(k) => k,
};
match (kind, self) {
(AxisKind::Section, Node::Section(_)) => true,
(AxisKind::Para, Node::Para(_)) => true,
(AxisKind::Run, Node::Run(_)) => true,
(AxisKind::Cell, Node::Cell(_)) => true,
(AxisKind::Control, Node::Control(_)) => true,
(k, Node::Control(c)) => control_axis(c) == Some(k),
_ => false,
}
}
pub fn axis_name(&self) -> &'static str {
match self {
Node::Section(_) => "section",
Node::Para(_) => "para",
Node::Run(_) => "run",
Node::Cell(_) => "cell",
Node::Control(c) => control_axis(c).map_or("control", AxisKind::name),
}
}
pub fn text(&self) -> Option<String> {
match self {
Node::Section(s) => Some(join_paragraphs(&s.paragraphs)),
Node::Para(p) => Some(p.text.clone()),
Node::Run(r) => Some(r.text().to_string()),
Node::Cell(c) => Some(join_paragraphs(&c.paragraphs)),
Node::Control(c) => paragraphs_of_control(c).map(join_paragraphs),
}
}
}
fn join_paragraphs(paras: &[Paragraph]) -> String {
let mut out = String::new();
for (i, p) in paras.iter().enumerate() {
if i > 0 {
out.push('\n');
}
out.push_str(&p.text);
}
out
}
pub fn paragraphs_of_control(control: &Control) -> Option<&[Paragraph]> {
match control {
Control::Footnote(f) => Some(&f.paragraphs),
Control::Endnote(e) => Some(&e.paragraphs),
Control::Header(h) => Some(&h.paragraphs),
Control::Footer(f) => Some(&f.paragraphs),
_ => None,
}
}
pub fn control_axis(control: &Control) -> Option<AxisKind> {
match control {
Control::Table(_) => Some(AxisKind::Table),
Control::Picture(_) => Some(AxisKind::Picture),
Control::Equation(_) => Some(AxisKind::Equation),
Control::Field(_) => Some(AxisKind::Field),
Control::Footnote(_) => Some(AxisKind::Footnote),
Control::Endnote(_) => Some(AxisKind::Endnote),
Control::Header(_) => Some(AxisKind::Header),
Control::Footer(_) => Some(AxisKind::Footer),
Control::Bookmark(_) => Some(AxisKind::Bookmark),
Control::Hyperlink(_) => Some(AxisKind::Hyperlink),
Control::Shape(_) => Some(AxisKind::Shape),
_ => None,
}
}
pub fn control_kind_name(control: &Control) -> &'static str {
if let Some(axis) = control_axis(control) {
return axis.name();
}
match control {
Control::SectionDef(_) => "sectionDef",
Control::ColumnDef(_) => "columnDef",
Control::AutoNumber(_) => "autoNumber",
Control::NewNumber(_) => "newNumber",
Control::PageNumberPos(_) => "pageNumberPos",
Control::Ruby(_) => "ruby",
Control::CharOverlap(_) => "charOverlap",
Control::PageHide(_) => "pageHide",
Control::HiddenComment(_) => "hiddenComment",
Control::Form(_) => "form",
Control::Unknown(_) => "unknown",
_ => "control",
}
}
#[derive(Debug, Clone)]
pub struct NodeRef<'d> {
pub id: NodeId,
pub node: Node<'d>,
pub index: usize,
pub sibling_count: usize,
}
#[derive(Debug, Clone, Default)]
pub struct PathStack {
steps: Vec<NodeStep>,
}
impl PathStack {
pub fn new() -> PathStack {
PathStack { steps: Vec::new() }
}
pub fn push(&mut self, step: NodeStep) {
self.steps.push(step);
}
pub fn pop(&mut self) {
self.steps.pop();
}
pub fn snapshot(&self) -> NodeId {
NodeId {
steps: self.steps.clone(),
}
}
pub fn depth(&self) -> usize {
self.steps.len()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::paragraph::CharShapeRef;
fn para_with(text: &str, shapes: &[(u32, u32)]) -> Paragraph {
let mut p = Paragraph {
text: text.to_string(),
..Default::default()
};
let mut utf16 = 0u32;
for ch in text.chars() {
p.char_offsets.push(utf16);
utf16 += ch.len_utf16() as u32;
}
p.char_shapes = shapes
.iter()
.map(|(start_pos, char_shape_id)| CharShapeRef {
start_pos: *start_pos,
char_shape_id: *char_shape_id,
})
.collect();
p
}
#[test]
fn node_id_renders_as_a_path() {
let id = NodeId::root()
.child(NodeStep::Section(0))
.child(NodeStep::Para(3))
.child(NodeStep::Control(0))
.child(NodeStep::Cell(5));
assert_eq!(id.to_string(), "/section[0]/para[3]/control[0]/cell[5]");
assert_eq!(NodeId::root().to_string(), "/");
}
#[test]
fn lexicographic_order_is_document_order() {
let a = NodeId::root()
.child(NodeStep::Section(0))
.child(NodeStep::Para(1));
let b = NodeId::root()
.child(NodeStep::Section(0))
.child(NodeStep::Para(2));
let c = NodeId::root()
.child(NodeStep::Section(1))
.child(NodeStep::Para(0));
let mut v = vec![c.clone(), b.clone(), a.clone()];
v.sort();
assert_eq!(v, vec![a, b, c]);
}
#[test]
fn ancestry_excludes_self() {
let parent = NodeId::root().child(NodeStep::Section(0));
let child = parent.child(NodeStep::Para(0));
assert!(child.is_descendant_of(&parent));
assert!(!parent.is_descendant_of(&parent));
assert!(!parent.is_descendant_of(&child));
}
#[test]
fn siblings_share_a_parent() {
let base = NodeId::root().child(NodeStep::Section(0));
let a = base.child(NodeStep::Para(0));
let b = base.child(NodeStep::Para(1));
let other = NodeId::root()
.child(NodeStep::Section(1))
.child(NodeStep::Para(0));
assert!(a.is_sibling_of(&b));
assert!(!a.is_sibling_of(&other));
assert!(!NodeId::root().is_sibling_of(&NodeId::root()));
}
#[test]
fn runs_split_at_char_shape_boundaries() {
let p = para_with("abcdef", &[(0, 10), (3, 20)]);
let runs = runs_of(&p);
assert_eq!(runs.len(), 2);
assert_eq!(runs[0].text(), "abc");
assert_eq!(runs[0].char_shape_id(), 10);
assert_eq!(runs[1].text(), "def");
assert_eq!(runs[1].char_shape_id(), 20);
}
#[test]
fn runs_use_utf16_positions_not_byte_positions() {
let p = para_with("가나다라", &[(0, 1), (2, 2)]);
let runs = runs_of(&p);
assert_eq!(runs[0].text(), "가나");
assert_eq!(runs[1].text(), "다라");
}
#[test]
fn surrogate_pair_counts_as_two_utf16_units() {
let p = para_with("😀ab", &[(0, 1), (2, 2)]);
let runs = runs_of(&p);
assert_eq!(runs[0].text(), "😀");
assert_eq!(runs[1].text(), "ab");
}
#[test]
fn empty_char_shapes_yield_no_runs() {
let p = para_with("abc", &[]);
assert!(runs_of(&p).is_empty());
}
#[test]
fn corrupt_offsets_do_not_panic() {
let mut p = para_with("가나다", &[(0, 1), (99, 2)]);
p.char_offsets.clear();
let runs = runs_of(&p);
assert!(runs.iter().all(|r| !r.text().is_empty()));
}
#[test]
fn non_monotonic_shape_positions_are_skipped_not_panicked() {
let p = para_with("abcdef", &[(0, 1), (5, 2), (2, 3)]);
let runs = runs_of(&p);
assert!(runs.iter().all(|r| !r.text().is_empty()));
}
#[test]
fn first_shape_is_pulled_down_to_zero() {
let p = para_with("abcdef", &[(2, 7)]);
let runs = runs_of(&p);
assert_eq!(runs.len(), 1);
assert_eq!(runs[0].text(), "abcdef");
}
#[test]
fn every_control_specialization_is_addressable_as_a_kind() {
use super::super::ast::AXIS_NAMES;
for (_, kind) in AXIS_NAMES {
if kind.specializes() == Some(AxisKind::Control) {
assert!(
AXIS_NAMES.iter().any(|(n, _)| *n == kind.name()),
"`{}` 가 kind 어휘에 없다",
kind.name()
);
}
}
}
#[test]
fn path_stack_snapshots_the_current_path() {
let mut st = PathStack::new();
st.push(NodeStep::Section(2));
st.push(NodeStep::Para(7));
assert_eq!(st.snapshot().to_string(), "/section[2]/para[7]");
assert_eq!(st.depth(), 2);
st.pop();
assert_eq!(st.snapshot().to_string(), "/section[2]");
}
}