pub use super::suggest::{nearest, unknown_attr, unknown_axis};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Selector {
pub paths: Vec<Path>,
pub source: String,
}
impl Selector {
pub fn result_axes(&self) -> Vec<Axis> {
let mut out: Vec<Axis> = self
.paths
.iter()
.filter_map(|p| p.steps.last().map(|s| s.axis))
.collect();
out.sort_by_key(|a| a.name());
out.dedup();
out
}
pub fn max_nesting(&self) -> usize {
self.paths
.iter()
.flat_map(|p| p.steps.iter())
.flat_map(|s| s.preds.iter())
.map(|p| match p {
Pred::Pseudo(Pseudo::Has(inner)) | Pred::Pseudo(Pseudo::Not(inner)) => {
1 + inner.max_nesting()
}
_ => 0,
})
.max()
.unwrap_or(0)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Path {
pub steps: Vec<Step>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Step {
pub combinator: Combinator,
pub axis: Axis,
pub preds: Vec<Pred>,
pub offset: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Combinator {
Root,
Descendant,
Child,
NextSibling,
FollowingSibling,
}
impl Combinator {
pub const fn symbol(self) -> &'static str {
match self {
Combinator::Root => "",
Combinator::Descendant => " ",
Combinator::Child => ">",
Combinator::NextSibling => "+",
Combinator::FollowingSibling => "~",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Axis {
Any,
Kind(AxisKind),
}
impl Axis {
pub const fn name(self) -> &'static str {
match self {
Axis::Any => "*",
Axis::Kind(k) => k.name(),
}
}
pub fn attributes(self) -> &'static [AttrDef] {
match self {
Axis::Any => COMMON_ATTRS,
Axis::Kind(k) => k.attributes(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum AxisKind {
Section,
Para,
Run,
Control,
Table,
Cell,
Picture,
Equation,
Field,
Footnote,
Endnote,
Header,
Footer,
Bookmark,
Hyperlink,
Shape,
}
pub const AXIS_NAMES: &[(&str, AxisKind)] = &[
("section", AxisKind::Section),
("para", AxisKind::Para),
("run", AxisKind::Run),
("control", AxisKind::Control),
("table", AxisKind::Table),
("cell", AxisKind::Cell),
("picture", AxisKind::Picture),
("equation", AxisKind::Equation),
("field", AxisKind::Field),
("footnote", AxisKind::Footnote),
("endnote", AxisKind::Endnote),
("header", AxisKind::Header),
("footer", AxisKind::Footer),
("bookmark", AxisKind::Bookmark),
("hyperlink", AxisKind::Hyperlink),
("shape", AxisKind::Shape),
];
impl AxisKind {
pub fn from_name(name: &str) -> Option<AxisKind> {
AXIS_NAMES.iter().find(|(n, _)| *n == name).map(|(_, k)| *k)
}
pub const fn name(self) -> &'static str {
match self {
AxisKind::Section => "section",
AxisKind::Para => "para",
AxisKind::Run => "run",
AxisKind::Control => "control",
AxisKind::Table => "table",
AxisKind::Cell => "cell",
AxisKind::Picture => "picture",
AxisKind::Equation => "equation",
AxisKind::Field => "field",
AxisKind::Footnote => "footnote",
AxisKind::Endnote => "endnote",
AxisKind::Header => "header",
AxisKind::Footer => "footer",
AxisKind::Bookmark => "bookmark",
AxisKind::Hyperlink => "hyperlink",
AxisKind::Shape => "shape",
}
}
pub const fn doc(self) -> &'static str {
match self {
AxisKind::Section => "구역 — 문서의 최상위 분할",
AxisKind::Para => "문단 — 구역·셀·각주·머리말 안 어디에 있든 같은 축",
AxisKind::Run => "글자 모양이 같은 연속 구간",
AxisKind::Control => "컨트롤 일반 — 표·그림·필드 등의 상위 축",
AxisKind::Table => "표",
AxisKind::Cell => "표의 셀",
AxisKind::Picture => "그림",
AxisKind::Equation => "수식",
AxisKind::Field => "필드 컨트롤 — 누름틀·메모 등",
AxisKind::Footnote => "각주",
AxisKind::Endnote => "미주",
AxisKind::Header => "머리말",
AxisKind::Footer => "꼬리말",
AxisKind::Bookmark => "책갈피",
AxisKind::Hyperlink => "하이퍼링크",
AxisKind::Shape => "그리기 개체",
}
}
pub const fn specializes(self) -> Option<AxisKind> {
match self {
AxisKind::Table
| AxisKind::Picture
| AxisKind::Equation
| AxisKind::Field
| AxisKind::Footnote
| AxisKind::Endnote
| AxisKind::Header
| AxisKind::Footer
| AxisKind::Bookmark
| AxisKind::Hyperlink
| AxisKind::Shape => Some(AxisKind::Control),
_ => None,
}
}
pub const fn holds_paragraphs(self) -> bool {
matches!(
self,
AxisKind::Section
| AxisKind::Cell
| AxisKind::Footnote
| AxisKind::Endnote
| AxisKind::Header
| AxisKind::Footer
)
}
pub const fn attributes(self) -> &'static [AttrDef] {
match self {
AxisKind::Section => SECTION_ATTRS,
AxisKind::Para => PARA_ATTRS,
AxisKind::Run => RUN_ATTRS,
AxisKind::Control => CONTROL_ATTRS,
AxisKind::Table => TABLE_ATTRS,
AxisKind::Cell => CELL_ATTRS,
AxisKind::Field => FIELD_ATTRS,
AxisKind::Hyperlink => HYPERLINK_ATTRS,
AxisKind::Bookmark => BOOKMARK_ATTRS,
_ => CONTROL_ATTRS,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AttrDef {
pub name: &'static str,
pub ty: AttrType,
pub doc: &'static str,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AttrType {
Str,
Int,
Bool,
}
impl AttrType {
pub const fn accepts(self, op: CmpOp) -> bool {
match self {
AttrType::Str => !matches!(op, CmpOp::Gt | CmpOp::Lt | CmpOp::Ge | CmpOp::Le),
AttrType::Int => matches!(
op,
CmpOp::Eq | CmpOp::Ne | CmpOp::Gt | CmpOp::Lt | CmpOp::Ge | CmpOp::Le
),
AttrType::Bool => matches!(op, CmpOp::Eq | CmpOp::Ne),
}
}
pub const fn as_str(self) -> &'static str {
match self {
AttrType::Str => "string",
AttrType::Int => "integer",
AttrType::Bool => "boolean",
}
}
}
pub const COMMON_ATTRS: &[AttrDef] = &[AttrDef {
name: "index",
ty: AttrType::Int,
doc: "형제 중 0 기준 순번",
}];
const SECTION_ATTRS: &[AttrDef] = &[
AttrDef {
name: "index",
ty: AttrType::Int,
doc: "구역 순번 (0 기준)",
},
AttrDef {
name: "paras",
ty: AttrType::Int,
doc: "직계 문단 수",
},
];
const PARA_ATTRS: &[AttrDef] = &[
AttrDef {
name: "index",
ty: AttrType::Int,
doc: "형제 문단 중 순번 (0 기준)",
},
AttrDef {
name: "text",
ty: AttrType::Str,
doc: "문단 텍스트 (제어문자 제외)",
},
AttrDef {
name: "len",
ty: AttrType::Int,
doc: "텍스트 문자 수 (제어문자 제외)",
},
AttrDef {
name: "styleId",
ty: AttrType::Int,
doc: "문단 스타일 ID",
},
AttrDef {
name: "shapeId",
ty: AttrType::Int,
doc: "문단 모양 ID",
},
AttrDef {
name: "empty",
ty: AttrType::Bool,
doc: "텍스트가 비었는가 (공백만 있어도 참)",
},
AttrDef {
name: "controls",
ty: AttrType::Int,
doc: "직계 컨트롤 수",
},
];
const RUN_ATTRS: &[AttrDef] = &[
AttrDef {
name: "index",
ty: AttrType::Int,
doc: "문단 안 구간 순번 (0 기준)",
},
AttrDef {
name: "text",
ty: AttrType::Str,
doc: "구간 텍스트",
},
AttrDef {
name: "len",
ty: AttrType::Int,
doc: "구간 문자 수",
},
AttrDef {
name: "charShapeId",
ty: AttrType::Int,
doc: "글자 모양 ID",
},
];
const CONTROL_ATTRS: &[AttrDef] = &[
AttrDef {
name: "index",
ty: AttrType::Int,
doc: "문단 안 컨트롤 순번 (0 기준)",
},
AttrDef {
name: "kind",
ty: AttrType::Str,
doc: "컨트롤 종류 이름 — 축 이름과 같은 어휘",
},
AttrDef {
name: "inline",
ty: AttrType::Bool,
doc: "글자처럼 취급되는가",
},
];
const TABLE_ATTRS: &[AttrDef] = &[
AttrDef {
name: "index",
ty: AttrType::Int,
doc: "문단 안 컨트롤 순번 (0 기준)",
},
AttrDef {
name: "kind",
ty: AttrType::Str,
doc: "컨트롤 종류 이름",
},
AttrDef {
name: "inline",
ty: AttrType::Bool,
doc: "글자처럼 취급되는가",
},
AttrDef {
name: "rows",
ty: AttrType::Int,
doc: "행 수",
},
AttrDef {
name: "cols",
ty: AttrType::Int,
doc: "열 수",
},
];
const CELL_ATTRS: &[AttrDef] = &[
AttrDef {
name: "index",
ty: AttrType::Int,
doc: "표 안 셀 순번 (행 우선, 0 기준)",
},
AttrDef {
name: "row",
ty: AttrType::Int,
doc: "행 주소 (0 기준)",
},
AttrDef {
name: "col",
ty: AttrType::Int,
doc: "열 주소 (0 기준)",
},
AttrDef {
name: "rowSpan",
ty: AttrType::Int,
doc: "행 병합 개수",
},
AttrDef {
name: "colSpan",
ty: AttrType::Int,
doc: "열 병합 개수",
},
AttrDef {
name: "text",
ty: AttrType::Str,
doc: "셀 안 문단 텍스트를 개행으로 이은 값",
},
AttrDef {
name: "header",
ty: AttrType::Bool,
doc: "제목 셀인가",
},
AttrDef {
name: "name",
ty: AttrType::Str,
doc: "셀 필드 이름 (없으면 어떤 값과도 같지 않다)",
},
];
const FIELD_ATTRS: &[AttrDef] = &[
AttrDef {
name: "index",
ty: AttrType::Int,
doc: "문단 안 컨트롤 순번 (0 기준)",
},
AttrDef {
name: "kind",
ty: AttrType::Str,
doc: "컨트롤 종류 이름",
},
AttrDef {
name: "inline",
ty: AttrType::Bool,
doc: "글자처럼 취급되는가",
},
AttrDef {
name: "name",
ty: AttrType::Str,
doc: "필드 이름 — CTRL_DATA 이름이 있으면 그것, 없으면 command",
},
AttrDef {
name: "type",
ty: AttrType::Str,
doc: "필드 타입 이름",
},
];
const HYPERLINK_ATTRS: &[AttrDef] = &[
AttrDef {
name: "index",
ty: AttrType::Int,
doc: "문단 안 컨트롤 순번 (0 기준)",
},
AttrDef {
name: "kind",
ty: AttrType::Str,
doc: "컨트롤 종류 이름",
},
AttrDef {
name: "inline",
ty: AttrType::Bool,
doc: "글자처럼 취급되는가",
},
];
const BOOKMARK_ATTRS: &[AttrDef] = &[
AttrDef {
name: "index",
ty: AttrType::Int,
doc: "문단 안 컨트롤 순번 (0 기준)",
},
AttrDef {
name: "kind",
ty: AttrType::Str,
doc: "컨트롤 종류 이름",
},
AttrDef {
name: "inline",
ty: AttrType::Bool,
doc: "글자처럼 취급되는가",
},
AttrDef {
name: "name",
ty: AttrType::Str,
doc: "책갈피 이름",
},
];
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Pred {
Attr(AttrPred),
Pseudo(Pseudo),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AttrPred {
pub name: String,
pub compare: Option<(CmpOp, Literal)>,
pub offset: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CmpOp {
Eq,
Ne,
Gt,
Lt,
Ge,
Le,
Prefix,
Suffix,
Substr,
Glob,
}
impl CmpOp {
pub const fn symbol(self) -> &'static str {
match self {
CmpOp::Eq => "=",
CmpOp::Ne => "!=",
CmpOp::Gt => ">",
CmpOp::Lt => "<",
CmpOp::Ge => ">=",
CmpOp::Le => "<=",
CmpOp::Prefix => "^=",
CmpOp::Suffix => "$=",
CmpOp::Substr => "*=",
CmpOp::Glob => "~=",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Literal {
Str(String),
Int(i64),
Bool(bool),
}
impl Literal {
pub const fn type_name(&self) -> &'static str {
match self {
Literal::Str(_) => "string",
Literal::Int(_) => "integer",
Literal::Bool(_) => "boolean",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Pseudo {
First,
Last,
Nth(i64),
Range { from: i64, to: i64 },
Contains(String),
Matches(String),
Empty,
Not(Box<Selector>),
Has(Box<Selector>),
}
impl Pseudo {
pub const fn name(&self) -> &'static str {
match self {
Pseudo::First => "first",
Pseudo::Last => "last",
Pseudo::Nth(_) => "nth",
Pseudo::Range { .. } => "range",
Pseudo::Contains(_) => "contains",
Pseudo::Matches(_) => "matches",
Pseudo::Empty => "empty",
Pseudo::Not(_) => "not",
Pseudo::Has(_) => "has",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PseudoDef {
pub name: &'static str,
pub arity: PseudoArity,
pub doc: &'static str,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PseudoArity {
None,
Int,
Str,
Range,
Selector,
}
pub const PSEUDO_DEFS: &[PseudoDef] = &[
PseudoDef {
name: "first",
arity: PseudoArity::None,
doc: "형제 중 첫째",
},
PseudoDef {
name: "last",
arity: PseudoArity::None,
doc: "형제 중 마지막",
},
PseudoDef {
name: "empty",
arity: PseudoArity::None,
doc: "텍스트가 비었다 (공백만 있어도 참)",
},
PseudoDef {
name: "nth",
arity: PseudoArity::Int,
doc: "0 기준 순번. 음수는 뒤에서 센다 (-1 = 마지막)",
},
PseudoDef {
name: "range",
arity: PseudoArity::Range,
doc: "0 기준 반열림 구간 a..b. 음수 인덱스 허용",
},
PseudoDef {
name: "contains",
arity: PseudoArity::Str,
doc: "텍스트 부분 일치",
},
PseudoDef {
name: "matches",
arity: PseudoArity::Str,
doc: "글롭 일치 — * ? [abc] [a-z] [!abc]",
},
PseudoDef {
name: "not",
arity: PseudoArity::Selector,
doc: "중첩 선택자에 걸리지 않는 것만",
},
PseudoDef {
name: "has",
arity: PseudoArity::Selector,
doc: "자손 중 중첩 선택자에 걸리는 것이 있는 것만",
},
];
impl PseudoDef {
pub fn from_name(name: &str) -> Option<&'static PseudoDef> {
PSEUDO_DEFS.iter().find(|d| d.name == name)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_axis_name_round_trips() {
for (name, kind) in AXIS_NAMES {
assert_eq!(AxisKind::from_name(name), Some(*kind));
assert_eq!(kind.name(), *name);
}
}
#[test]
fn specialized_axes_expose_the_parent_attributes() {
for attr in AxisKind::Control.attributes() {
assert!(
AxisKind::Table
.attributes()
.iter()
.any(|a| a.name == attr.name),
"table 축에 control 속성 `{}` 이 없다",
attr.name
);
}
}
#[test]
fn specialization_never_points_at_a_containment_parent() {
assert_eq!(AxisKind::Cell.specializes(), None);
assert_eq!(AxisKind::Table.specializes(), Some(AxisKind::Control));
}
#[test]
fn wildcard_axis_exposes_only_common_attributes() {
let names: Vec<&str> = Axis::Any.attributes().iter().map(|a| a.name).collect();
assert_eq!(names, vec!["index"]);
}
#[test]
fn string_attributes_reject_ordering_operators() {
assert!(!AttrType::Str.accepts(CmpOp::Ge));
assert!(AttrType::Str.accepts(CmpOp::Prefix));
assert!(!AttrType::Int.accepts(CmpOp::Substr));
assert!(AttrType::Bool.accepts(CmpOp::Ne));
assert!(!AttrType::Bool.accepts(CmpOp::Gt));
}
#[test]
fn nearest_is_deterministic_under_ties() {
let forward = nearest("cellx", ["cell", "cells"]);
let backward = nearest("cellx", ["cells", "cell"]);
assert_eq!(forward, backward);
}
#[test]
fn nearest_gives_up_beyond_distance_two() {
assert_eq!(nearest("표", AXIS_NAMES.iter().map(|(n, _)| *n)), None);
}
#[test]
fn unknown_axis_suggests_the_close_one() {
let err = unknown_axis("tabel", 0);
assert_eq!(err.hint.as_deref(), Some("`table` 를 뜻했나"));
}
#[test]
fn unknown_attr_scopes_candidates_to_the_axis() {
let err = unknown_attr(Axis::Kind(AxisKind::Cell), "rowspan", 5);
assert!(err.expected.iter().any(|e| e == "rowSpan"));
assert!(!err.expected.iter().any(|e| e == "styleId"));
}
#[test]
fn pseudo_defs_cover_every_pseudo_variant_name() {
let variants = [
Pseudo::First,
Pseudo::Last,
Pseudo::Nth(0),
Pseudo::Range { from: 0, to: 1 },
Pseudo::Contains(String::new()),
Pseudo::Matches(String::new()),
Pseudo::Empty,
];
for v in variants {
assert!(
PseudoDef::from_name(v.name()).is_some(),
"사전에 `{}` 가 없다",
v.name()
);
}
assert!(PseudoDef::from_name("not").is_some());
assert!(PseudoDef::from_name("has").is_some());
}
#[test]
fn paragraph_holders_match_the_ir_shape() {
assert!(AxisKind::Cell.holds_paragraphs());
assert!(AxisKind::Section.holds_paragraphs());
assert!(AxisKind::Footnote.holds_paragraphs());
assert!(!AxisKind::Table.holds_paragraphs());
assert!(!AxisKind::Para.holds_paragraphs());
}
}