#![allow(dead_code)]
use std::ops::Range;
use crate::domain::binding::{
BindingError, Block, BlockKind, BoundTemplate, InlineContent, Scope, TextSpan,
};
use crate::domain::document::{Document, Role};
use crate::syntax::ast::Node as AstNode;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct TagRanges {
pub(crate) open: TextSpan,
pub(crate) elif_tags: Vec<TextSpan>,
pub(crate) else_tag: Option<TextSpan>,
pub(crate) close: TextSpan,
}
impl TagRanges {
pub(crate) fn first_separator(&self) -> usize {
self.elif_tags
.first()
.map(|tag| tag.start)
.or_else(|| self.else_tag.as_ref().map(|tag| tag.start))
.unwrap_or(self.close.start)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Placement {
BlockRange {
parent: Vec<usize>,
body: Range<usize>,
tags: TagRanges,
},
RowRange {
table: Vec<usize>,
body: Range<usize>,
tags: TagRanges,
},
SingleRow {
row: Vec<usize>,
index: usize,
tags: TagRanges,
},
ConditionalBlocks {
parent: Vec<usize>,
then_body: Range<usize>,
else_body: Option<Range<usize>>,
tags: TagRanges,
},
ConditionalRows {
table: Vec<usize>,
then_body: Range<usize>,
else_body: Option<Range<usize>>,
tags: TagRanges,
},
ConditionalInline {
paragraph: usize,
then_body: Range<usize>,
else_body: Option<Range<usize>>,
tags: TagRanges,
},
}
impl Placement {
pub(crate) fn tags(&self) -> &TagRanges {
match self {
Placement::BlockRange { tags, .. }
| Placement::RowRange { tags, .. }
| Placement::SingleRow { tags, .. }
| Placement::ConditionalBlocks { tags, .. }
| Placement::ConditionalRows { tags, .. }
| Placement::ConditionalInline { tags, .. } => tags,
}
}
pub(crate) fn body(&self) -> Option<&Range<usize>> {
match self {
Placement::BlockRange { body, .. } | Placement::RowRange { body, .. } => Some(body),
Placement::ConditionalBlocks { then_body, .. }
| Placement::ConditionalRows { then_body, .. }
| Placement::ConditionalInline { then_body, .. } => Some(then_body),
Placement::SingleRow { .. } => None,
}
}
pub(crate) fn else_body(&self) -> Option<&Range<usize>> {
match self {
Placement::ConditionalBlocks { else_body, .. }
| Placement::ConditionalRows { else_body, .. }
| Placement::ConditionalInline { else_body, .. } => else_body.as_ref(),
_ => None,
}
}
pub(crate) fn is_loop(&self) -> bool {
matches!(
self,
Placement::BlockRange { .. } | Placement::RowRange { .. } | Placement::SingleRow { .. }
)
}
}
pub(crate) fn classify_block(
document: &Document,
block: &Block,
part: &str,
) -> Result<Placement, BindingError> {
match (&block.scope, &block.kind) {
(Scope::Blocks(parent), BlockKind::Loop { .. }) => {
if body_wraps_table(document, parent, &block.then_body) {
return Err(BindingError::LoopWrapsTable {
part: part.to_owned(),
span: block.open.span.clone(),
});
}
Ok(Placement::BlockRange {
parent: parent.clone(),
body: block.then_body.clone(),
tags: tag_ranges(block),
})
}
(Scope::Rows(table), BlockKind::Loop { .. }) => Ok(Placement::RowRange {
table: table.clone(),
body: block.then_body.clone(),
tags: tag_ranges(block),
}),
(Scope::Blocks(parent), BlockKind::Conditional { .. }) => {
Ok(Placement::ConditionalBlocks {
parent: parent.clone(),
then_body: block.then_body.clone(),
else_body: block.else_body.clone(),
tags: tag_ranges(block),
})
}
(Scope::Rows(table), BlockKind::Conditional { .. }) => Ok(Placement::ConditionalRows {
table: table.clone(),
then_body: block.then_body.clone(),
else_body: block.else_body.clone(),
tags: tag_ranges(block),
}),
}
}
fn tag_ranges(block: &Block) -> TagRanges {
TagRanges {
open: block.open.span.clone(),
elif_tags: block
.elif_sites
.iter()
.map(|site| site.span.clone())
.collect(),
else_tag: block.else_site.as_ref().map(|site| site.span.clone()),
close: block.close.span.clone(),
}
}
fn body_wraps_table(document: &Document, parent: &[usize], body: &Range<usize>) -> bool {
let Some(container) = document.root().at(parent) else {
return false;
};
body.clone().any(|index| {
container
.children()
.get(index)
.and_then(|node| node.as_element())
.is_some_and(|element| element.role() == Role::Table)
})
}
pub(crate) fn classify(
document: &Document,
bound: &BoundTemplate,
) -> Result<Vec<Placement>, BindingError> {
let mut placements = Vec::new();
let mut errors = None;
for block in bound.blocks() {
walk_block(document, block, bound.part(), &mut placements, &mut errors);
}
for content in bound.inline() {
match classify_inline(bound, content) {
Ok(found) => placements.extend(found),
Err(error) => {
if errors.is_none() {
errors = Some(error);
}
}
}
}
if let Some(error) = errors {
return Err(error);
}
placements.sort_by_key(|placement| placement.tags().open.start);
Ok(placements)
}
fn walk_block(
document: &Document,
block: &Block,
part: &str,
placements: &mut Vec<Placement>,
errors: &mut Option<BindingError>,
) {
match classify_block(document, block, part) {
Ok(placement) => placements.push(placement),
Err(error) => {
if errors.is_none() {
*errors = Some(error);
}
}
}
for child in &block.children {
walk_block(document, child, part, placements, errors);
}
}
fn classify_inline(
bound: &BoundTemplate,
content: &InlineContent,
) -> Result<Vec<Placement>, BindingError> {
let paragraph =
bound
.paragraphs()
.get(content.paragraph)
.ok_or_else(|| BindingError::Syntax {
part: bound.part().to_owned(),
message: "inline content belongs to no paragraph".to_owned(),
})?;
let text = paragraph.text();
let mut placements = Vec::new();
for node in &content.nodes {
match node {
AstNode::If(if_node) => {
let node_span = &if_node.span;
let tags =
inline_tag_ranges(text, node_span.start, node_span.end).ok_or_else(|| {
BindingError::Syntax {
part: bound.part().to_owned(),
message: "inline conditional has no matching tags".to_owned(),
}
})?;
let then_body = tags.open.end..tags.first_separator();
let else_body = tags.else_tag.as_ref().map(|tag| tag.end..tags.close.start);
placements.push(Placement::ConditionalInline {
paragraph: content.paragraph,
then_body,
else_body,
tags,
});
}
AstNode::For(for_node) => {
let Some(row_index) = paragraph.enclosing_row else {
return Err(BindingError::UnsupportedInlineLoop {
part: bound.part().to_owned(),
path: paragraph.path.clone(),
});
};
let row = bound
.rows()
.get(row_index)
.ok_or_else(|| BindingError::Syntax {
part: bound.part().to_owned(),
message: "inline loop has no row".to_owned(),
})?;
let tags = inline_tag_ranges(text, for_node.span.start, for_node.span.end)
.ok_or_else(|| BindingError::Syntax {
part: bound.part().to_owned(),
message: "inline loop has no matching tags".to_owned(),
})?;
placements.push(Placement::SingleRow {
row: row.path.clone(),
index: row.path.last().copied().unwrap_or(0),
tags,
});
}
_ => {}
}
}
Ok(placements)
}
enum InlineTagKind {
Open,
Close,
Elif,
Else,
Other,
}
fn inline_tag_kind(inner: &str) -> InlineTagKind {
let inner = inner.trim();
if inner == "else" {
InlineTagKind::Else
} else if inner == "endif" || inner == "endfor" {
InlineTagKind::Close
} else if has_word_prefix(inner, "elif") {
InlineTagKind::Elif
} else if has_word_prefix(inner, "if") || has_word_prefix(inner, "for") {
InlineTagKind::Open
} else {
InlineTagKind::Other
}
}
fn has_word_prefix(inner: &str, word: &str) -> bool {
inner
.strip_prefix(word)
.is_some_and(|rest| rest.starts_with(char::is_whitespace))
}
fn inline_tag_ranges(text: &str, start: usize, end: usize) -> Option<TagRanges> {
let slice = &text[start..end];
let mut tags = Vec::new();
let mut from = 0;
while let Some(relative) = slice[from..].find("{%") {
let open = from + relative;
let Some(close) = slice[open + 2..].find("%}") else {
break;
};
let close = open + 2 + close + 2;
tags.push(start + open..start + close);
from = close;
if from >= slice.len() {
break;
}
}
if tags.len() < 2 {
return None;
}
let mut depth = 0usize;
let mut elif_tags = Vec::new();
let mut else_tag = None;
for tag in &tags {
match inline_tag_kind(&text[tag.start + 2..tag.end - 2]) {
InlineTagKind::Open => depth += 1,
InlineTagKind::Close => depth = depth.saturating_sub(1),
InlineTagKind::Elif if depth == 1 => elif_tags.push(tag.clone()),
InlineTagKind::Else if depth == 1 => else_tag = Some(tag.clone()),
InlineTagKind::Elif | InlineTagKind::Else | InlineTagKind::Other => {}
}
}
let open = tags.first()?.clone();
let close = tags.last()?.clone();
Some(TagRanges {
open,
elif_tags,
else_tag,
close,
})
}
#[cfg(test)]
mod tests {
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
use super::*;
use crate::domain::binding::bind;
use crate::domain::document::{Element, Node, TextNode};
fn element(name: &str, role: Role, children: Vec<Node>) -> Element {
Element::new(
name.to_owned(),
role,
format!("<{name}>").into_bytes(),
format!("</{name}>").into_bytes(),
false,
children,
)
}
fn text(value: &str) -> Node {
Node::Text(TextNode::original(
value.as_bytes().to_vec(),
value.to_owned(),
))
}
fn run(value: &str) -> Node {
Node::Element(element(
"w:r",
Role::Run,
vec![Node::Element(element("w:t", Role::Text, vec![text(value)]))],
))
}
fn paragraph(value: &str) -> Node {
Node::Element(element("w:p", Role::Paragraph, vec![run(value)]))
}
fn cell(paragraphs: Vec<Node>) -> Node {
Node::Element(element("w:tc", Role::Cell, paragraphs))
}
fn row(cells: Vec<Node>) -> Node {
Node::Element(element("w:tr", Role::Row, cells))
}
fn table(rows: Vec<Node>) -> Node {
Node::Element(element("w:tbl", Role::Table, rows))
}
fn document(children: Vec<Node>) -> Document {
let body = element("w:body", Role::Body, children);
let root = element("w:document", Role::Document, vec![Node::Element(body)]);
Document::new(Vec::new(), root, Vec::new(), "w".to_owned())
}
fn classify_all(children: Vec<Node>) -> Result<Vec<Placement>, BindingError> {
let document = document(children);
let bound = bind(&document, "word/document.xml")?;
classify(&document, &bound)
}
#[test]
fn classifies_every_row_of_the_placement_table() {
struct Case {
name: &'static str,
children: Vec<Node>,
check: fn(&Placement) -> bool,
}
let cases = vec![
Case {
name: "block range",
children: vec![
paragraph("{% for item in items %}"),
paragraph("{{item.name}}"),
paragraph("{% endfor %}"),
],
check: |placement| matches!(placement, Placement::BlockRange { body, .. } if *body == (1..2)),
},
Case {
name: "row range",
children: vec![table(vec![
row(vec![cell(vec![paragraph("{% for item in items %}")])]),
row(vec![cell(vec![paragraph("{{item.name}}")])]),
row(vec![cell(vec![paragraph("{% endfor %}")])]),
])],
check: |placement| matches!(placement, Placement::RowRange { body, .. } if *body == (1..2)),
},
Case {
name: "single row",
children: vec![table(vec![row(vec![cell(vec![paragraph(
"{% for item in items %}{{item}}{% endfor %}",
)])])])],
check: |placement| matches!(placement, Placement::SingleRow { index, .. } if *index == 0),
},
Case {
name: "conditional blocks",
children: vec![
paragraph("{% if admin %}"),
paragraph("yes"),
paragraph("{% endif %}"),
],
check: |placement| matches!(placement, Placement::ConditionalBlocks { then_body, .. } if *then_body == (1..2)),
},
Case {
name: "conditional rows",
children: vec![table(vec![
row(vec![cell(vec![paragraph("{% if admin %}")])]),
row(vec![cell(vec![paragraph("yes")])]),
row(vec![cell(vec![paragraph("{% endif %}")])]),
])],
check: |placement| matches!(placement, Placement::ConditionalRows { then_body, .. } if *then_body == (1..2)),
},
Case {
name: "conditional inline",
children: vec![paragraph("{% if admin %}yes{% else %}no{% endif %}")],
check: |placement| matches!(placement, Placement::ConditionalInline { .. }),
},
];
for case in cases {
let placements = classify_all(case.children)
.unwrap_or_else(|error| panic!("{}: {error}", case.name));
assert_eq!(placements.len(), 1, "{}", case.name);
assert!((case.check)(&placements[0]), "{}", case.name);
}
}
#[test]
fn an_inline_conditional_reports_both_branches_and_three_tags() {
let placements =
classify_all(vec![paragraph("a{% if x %}b{% else %}c{% endif %}d")]).unwrap();
let Placement::ConditionalInline {
then_body,
else_body,
tags,
..
} = &placements[0]
else {
panic!("expected an inline conditional");
};
assert_eq!(
&"a{% if x %}b{% else %}c{% endif %}d"[then_body.clone()],
"b"
);
assert_eq!(
&"a{% if x %}b{% else %}c{% endif %}d"[else_body.clone().unwrap()],
"c"
);
assert_eq!(
&"a{% if x %}b{% else %}c{% endif %}d"[tags.open.clone()],
"{% if x %}"
);
assert_eq!(
&"a{% if x %}b{% else %}c{% endif %}d"[tags.close.clone()],
"{% endif %}"
);
}
#[test]
fn a_conditional_without_else_has_an_empty_false_branch() {
let placements = classify_all(vec![
paragraph("{% if x %}"),
paragraph("yes"),
paragraph("{% endif %}"),
])
.unwrap();
assert_eq!(placements[0].else_body(), None);
}
#[test]
fn a_loop_wrapping_a_table_is_rejected() {
let error = classify_all(vec![
paragraph("{% for item in items %}"),
table(vec![row(vec![cell(vec![paragraph("{{item.name}}")])])]),
paragraph("{% endfor %}"),
])
.unwrap_err();
assert!(matches!(error, BindingError::LoopWrapsTable { .. }));
}
#[test]
fn nested_blocks_are_all_classified() {
let placements = classify_all(vec![
paragraph("{% for row in rows %}"),
paragraph("{% if row.show %}"),
paragraph("{{row.name}}"),
paragraph("{% endif %}"),
paragraph("{% endfor %}"),
])
.unwrap();
assert_eq!(placements.len(), 2);
assert!(placements[0].is_loop());
assert!(!placements[1].is_loop());
}
#[test]
fn placements_are_in_document_order() {
let placements = classify_all(vec![
paragraph("{{first}}"),
paragraph("{% if a %}x{% endif %}"),
paragraph("{% for item in items %}"),
paragraph("{{item.name}}"),
paragraph("{% endfor %}"),
])
.unwrap();
assert_eq!(placements.len(), 2);
assert!(placements[0].tags().open.start < placements[1].tags().open.start);
}
}