Skip to main content

docx_templating/domain/binding/
mod.rs

1//! Template binding.
2//!
3//! Binding connects the parsed template syntax to the document tree. It builds
4//! a document order map from paragraphs and rows to character ranges, finds the
5//! structural block tags that sit in their own paragraph or row, matches them
6//! into a block tree, and parses the remaining paragraphs as inline content.
7//!
8//! Every placement mistake is rejected here, at load time, with a typed error,
9//! so the evaluator and the renderer never have to guess.
10
11// The binding is consumed by the evaluator in a later ticket.
12#![allow(dead_code)]
13
14use std::ops::Range;
15
16use crate::domain::document::projection::{Projection, ProjectionError, ResolvedSlice, project};
17use crate::domain::document::{Document, Element, Node, Role};
18use crate::syntax::ast::{Expression, Node as AstNode};
19use crate::syntax::parse_expression;
20
21/// A byte range in the concatenated template text.
22pub(crate) type TextSpan = Range<usize>;
23
24/// A bound paragraph and its place in the concatenated text.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub(crate) struct BoundParagraph {
27    /// Child indices from the root element to the paragraph.
28    pub(crate) path: Vec<usize>,
29    /// Start offset in the concatenated text.
30    pub(crate) text_start: usize,
31    /// End offset in the concatenated text.
32    pub(crate) text_end: usize,
33    /// The nearest enclosing table row, if any.
34    pub(crate) enclosing_row: Option<usize>,
35    /// The paragraph projection, used to resolve spans to text nodes.
36    pub(crate) projection: Projection,
37}
38
39impl BoundParagraph {
40    /// The paragraph text.
41    pub(crate) fn text(&self) -> &str {
42        self.projection.text()
43    }
44}
45
46/// A bound table row and its place in the concatenated text.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub(crate) struct BoundRow {
49    /// Child indices from the root element to the row.
50    pub(crate) path: Vec<usize>,
51    /// Child indices from the root element to the table that owns the row.
52    pub(crate) table_path: Vec<usize>,
53    /// Start offset in the concatenated text.
54    pub(crate) text_start: usize,
55    /// End offset in the concatenated text.
56    pub(crate) text_end: usize,
57    /// Index of the first bound paragraph in the row.
58    pub(crate) first_paragraph: usize,
59}
60
61/// The container a block lives in.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub(crate) enum Scope {
64    /// Sibling blocks inside a body, cell or block container.
65    Blocks(Vec<usize>),
66    /// Sibling rows inside a table.
67    Rows(Vec<usize>),
68}
69
70/// A tag found while binding.
71#[derive(Debug, Clone, PartialEq)]
72pub(crate) enum Tag {
73    /// `{% if expression %}`
74    IfStart(Expression),
75    /// `{% elif expression %}`
76    Elif(Expression),
77    /// `{% else %}`
78    Else,
79    /// `{% endif %}`
80    IfEnd,
81    /// `{% for item in iterable %}`
82    ForStart {
83        /// The loop variable name.
84        item: String,
85        /// The expression to iterate over.
86        iterable: Expression,
87    },
88    /// `{% endfor %}`
89    ForEnd,
90}
91
92impl Tag {
93    /// The tag name used in error messages.
94    fn name(&self) -> &'static str {
95        match self {
96            Tag::IfStart(_) => "{% if %}",
97            Tag::Elif(_) => "{% elif %}",
98            Tag::Else => "{% else %}",
99            Tag::IfEnd => "{% endif %}",
100            Tag::ForStart { .. } => "{% for %}",
101            Tag::ForEnd => "{% endfor %}",
102        }
103    }
104
105    /// Whether this tag opens a block.
106    fn is_open(&self) -> bool {
107        matches!(self, Tag::IfStart(_) | Tag::ForStart { .. })
108    }
109
110    /// Whether this tag closes a block.
111    fn is_close(&self) -> bool {
112        matches!(self, Tag::IfEnd | Tag::ForEnd)
113    }
114
115    /// Whether this closing tag belongs to the given opening tag.
116    fn closes(&self, open: &Tag) -> bool {
117        matches!(
118            (open, self),
119            (Tag::IfStart(_), Tag::IfEnd) | (Tag::ForStart { .. }, Tag::ForEnd)
120        )
121    }
122}
123
124/// A tag placed in the tree.
125#[derive(Debug, Clone, PartialEq)]
126pub(crate) struct TagSite {
127    /// Index into [`BoundTemplate::paragraphs`].
128    pub(crate) paragraph: usize,
129    /// Child indices from the root element to the paragraph.
130    pub(crate) path: Vec<usize>,
131    /// The sibling index of the marker paragraph or row.
132    pub(crate) index: usize,
133    /// The container the block lives in.
134    pub(crate) scope: Scope,
135    /// The tag text range in the concatenated text.
136    pub(crate) span: TextSpan,
137    /// The parsed tag.
138    pub(crate) tag: Tag,
139}
140
141/// The shape of a bound block.
142#[derive(Debug, Clone, PartialEq)]
143pub(crate) enum BlockKind {
144    /// A conditional with a then branch, optional `elif` branches and an
145    /// optional else branch.
146    Conditional {
147        /// The condition.
148        condition: Expression,
149        /// The `elif` conditions, in source order.
150        elifs: Vec<Expression>,
151        /// Whether an `{% else %}` tag is present.
152        has_else: bool,
153    },
154    /// A loop over an iterable.
155    Loop {
156        /// The loop variable name.
157        item: String,
158        /// The iterable expression.
159        iterable: Expression,
160    },
161}
162
163/// A block resolved at bind time.
164#[derive(Debug, Clone, PartialEq)]
165pub(crate) struct Block {
166    /// The block shape.
167    pub(crate) kind: BlockKind,
168    /// The container the block lives in.
169    pub(crate) scope: Scope,
170    /// The opening tag.
171    pub(crate) open: TagSite,
172    /// The closing tag.
173    pub(crate) close: TagSite,
174    /// The `{% elif %}` tags, in source order.
175    pub(crate) elif_sites: Vec<TagSite>,
176    /// The `{% else %}` tag, when present.
177    pub(crate) else_site: Option<TagSite>,
178    /// Sibling indices of the then branch inside the scope.
179    pub(crate) then_body: Range<usize>,
180    /// Sibling indices of the else branch inside the scope.
181    pub(crate) else_body: Option<Range<usize>>,
182    /// Blocks nested directly in this block.
183    pub(crate) children: Vec<Block>,
184}
185
186impl Block {
187    /// A short name used in error messages.
188    pub(crate) fn name(&self) -> &'static str {
189        match self.kind {
190            BlockKind::Conditional { .. } => "{% if %}",
191            BlockKind::Loop { .. } => "{% for %}",
192        }
193    }
194}
195
196/// The inline content of a paragraph.
197#[derive(Debug, Clone, PartialEq)]
198pub(crate) struct InlineContent {
199    /// Index into [`BoundTemplate::paragraphs`].
200    pub(crate) paragraph: usize,
201    /// The parsed nodes. Spans are relative to the paragraph text.
202    pub(crate) nodes: Vec<AstNode>,
203}
204
205/// A template bound to a document tree.
206#[derive(Debug, Clone, PartialEq)]
207pub(crate) struct BoundTemplate {
208    part: String,
209    text: String,
210    paragraphs: Vec<BoundParagraph>,
211    rows: Vec<BoundRow>,
212    blocks: Vec<Block>,
213    inline: Vec<InlineContent>,
214}
215
216/// An error raised while binding.
217///
218/// Every variant names the part and the block it came from, so a caller can
219/// match the cause without parsing the message.
220#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
221#[non_exhaustive]
222pub enum BindingError {
223    /// The template syntax could not be parsed.
224    #[error("template syntax error in {part}: {message}")]
225    Syntax {
226        /// The part name.
227        part: String,
228        /// The parser message.
229        message: String,
230    },
231
232    /// A template delimiter was found inside an element the model does not type.
233    #[error("template delimiter inside opaque element {element} in {part} at byte {offset}")]
234    TemplateInOpaqueElement {
235        /// The part name.
236        part: String,
237        /// The qualified element name.
238        element: String,
239        /// Offset of the delimiter within the opaque text.
240        offset: usize,
241    },
242
243    /// A structural tag shares its paragraph with other text.
244    #[error("a {container} tag in {part} shares its container with other text at {span:?}")]
245    TagSharesContainer {
246        /// The part name.
247        part: String,
248        /// The kind of container, such as `paragraph`.
249        container: &'static str,
250        /// The tag text range.
251        span: TextSpan,
252    },
253
254    /// A block opens in one container and closes in another.
255    #[error("block in {part} opens in {open:?} and closes in {close:?}")]
256    BodyCrossesContainer {
257        /// The part name.
258        part: String,
259        /// The opening container path.
260        open: Vec<usize>,
261        /// The closing container path.
262        close: Vec<usize>,
263    },
264
265    /// A loop body wraps a whole table.
266    #[error("loop in {part} wraps a whole table at {span:?}; loop over a table row instead")]
267    LoopWrapsTable {
268        /// The part name.
269        part: String,
270        /// The opening tag range.
271        span: TextSpan,
272    },
273
274    /// An inline loop appears outside a table row.
275    #[error("inline loop in {part} at paragraph {path:?} is outside a table row")]
276    UnsupportedInlineLoop {
277        /// The part name.
278        part: String,
279        /// The paragraph path.
280        path: Vec<usize>,
281    },
282
283    /// A paragraph holds two structural tags.
284    #[error("two structural tags in one block in {part} at {first:?} and {second:?}")]
285    MultipleTagsInBlock {
286        /// The part name.
287        part: String,
288        /// The block path.
289        path: Vec<usize>,
290        /// The first tag range.
291        first: TextSpan,
292        /// The second tag range.
293        second: TextSpan,
294    },
295
296    /// A block was opened and never closed.
297    #[error("unclosed block in {part} at {span:?}")]
298    UnclosedBlock {
299        /// The part name.
300        part: String,
301        /// The opening tag range.
302        span: TextSpan,
303    },
304
305    /// A closing tag has no opening tag.
306    #[error("unexpected tag in {part} at {span:?}")]
307    UnexpectedTag {
308        /// The part name.
309        part: String,
310        /// The tag range.
311        span: TextSpan,
312    },
313
314    /// A closing tag does not match the open block.
315    #[error("mismatched block in {part}: opened at {open:?} but closed at {close:?}")]
316    MismatchedBlock {
317        /// The part name.
318        part: String,
319        /// The opening tag range.
320        open: TextSpan,
321        /// The closing tag range.
322        close: TextSpan,
323    },
324}
325
326impl BindingError {
327    /// The part the error refers to.
328    pub(crate) fn part(&self) -> &str {
329        match self {
330            BindingError::Syntax { part, .. }
331            | BindingError::TemplateInOpaqueElement { part, .. }
332            | BindingError::TagSharesContainer { part, .. }
333            | BindingError::BodyCrossesContainer { part, .. }
334            | BindingError::LoopWrapsTable { part, .. }
335            | BindingError::UnsupportedInlineLoop { part, .. }
336            | BindingError::MultipleTagsInBlock { part, .. }
337            | BindingError::UnclosedBlock { part, .. }
338            | BindingError::UnexpectedTag { part, .. }
339            | BindingError::MismatchedBlock { part, .. } => part,
340        }
341    }
342}
343
344impl BoundTemplate {
345    /// The part name.
346    pub(crate) fn part(&self) -> &str {
347        &self.part
348    }
349
350    /// The concatenated text that was parsed.
351    pub(crate) fn text(&self) -> &str {
352        &self.text
353    }
354
355    /// The bound paragraphs in document order.
356    pub(crate) fn paragraphs(&self) -> &[BoundParagraph] {
357        &self.paragraphs
358    }
359
360    /// The bound rows in document order.
361    pub(crate) fn rows(&self) -> &[BoundRow] {
362        &self.rows
363    }
364
365    /// The top level blocks in document order.
366    pub(crate) fn blocks(&self) -> &[Block] {
367        &self.blocks
368    }
369
370    /// The inline content of the paragraphs that hold no structural tag.
371    pub(crate) fn inline(&self) -> &[InlineContent] {
372        &self.inline
373    }
374
375    /// The paragraph that contains the given text offset.
376    pub(crate) fn paragraph_at(&self, offset: usize) -> Option<usize> {
377        self.paragraphs
378            .iter()
379            .position(|paragraph| contains(paragraph.text_start, paragraph.text_end, offset))
380    }
381
382    /// The row that contains the given text offset.
383    pub(crate) fn row_at(&self, offset: usize) -> Option<usize> {
384        self.rows
385            .iter()
386            .position(|row| contains(row.text_start, row.text_end, offset))
387    }
388
389    /// Paragraphs fully covered by the half open range `[start, end)`.
390    ///
391    /// An empty paragraph is covered when its position falls inside the range.
392    pub(crate) fn paragraphs_in_range(&self, range: TextSpan) -> Vec<usize> {
393        self.paragraphs
394            .iter()
395            .enumerate()
396            .filter(|(_, paragraph)| covered(paragraph.text_start, paragraph.text_end, &range))
397            .map(|(index, _)| index)
398            .collect()
399    }
400
401    /// Rows fully covered by the half open range `[start, end)`.
402    pub(crate) fn rows_in_range(&self, range: TextSpan) -> Vec<usize> {
403        self.rows
404            .iter()
405            .enumerate()
406            .filter(|(_, row)| covered(row.text_start, row.text_end, &range))
407            .map(|(index, _)| index)
408            .collect()
409    }
410
411    /// Whether a span starts and ends inside the same paragraph.
412    pub(crate) fn is_inline(&self, span: &TextSpan) -> bool {
413        match (
414            self.paragraph_at(span.start),
415            self.paragraph_at(span.end.saturating_sub(1)),
416        ) {
417            (Some(left), Some(right)) => left == right,
418            _ => false,
419        }
420    }
421
422    /// Resolve a range of a paragraph to the text nodes it covers.
423    ///
424    /// `span` is relative to the paragraph text.
425    pub(crate) fn resolve_inline(
426        &self,
427        paragraph: usize,
428        span: &TextSpan,
429    ) -> Result<Vec<ResolvedSlice>, ProjectionError> {
430        match self.paragraphs.get(paragraph) {
431            Some(paragraph) => paragraph.projection.resolve(span.start, span.end),
432            None => Ok(Vec::new()),
433        }
434    }
435}
436
437/// Bind the template syntax in a document tree.
438pub(crate) fn bind(document: &Document, part: &str) -> Result<BoundTemplate, BindingError> {
439    let mut collector = Collector::new(part);
440    let mut path = Vec::new();
441    collector.walk(document.root(), &mut path, None);
442
443    if let Some(error) = collector.error {
444        return Err(error);
445    }
446
447    let Collector {
448        paragraphs,
449        rows,
450        text,
451        containers,
452        ..
453    } = collector;
454
455    let sites = marker_sites(&paragraphs, &rows, &text, part)?;
456    let blocks = match_blocks(&sites, &containers, part)?;
457    let inline = collect_inline(&paragraphs, &rows, &sites, part)?;
458
459    Ok(BoundTemplate {
460        part: part.to_owned(),
461        text,
462        paragraphs,
463        rows,
464        blocks,
465        inline,
466    })
467}
468
469/// The concatenated text of a part and one range per paragraph.
470///
471/// Diagnostics use this to turn a span from a [`BindingError`] into a line, and
472/// it walks the tree exactly as [`bind`] does, so the offsets always line up.
473pub(crate) fn text_view(document: &Document, part: &str) -> (String, Vec<Range<usize>>) {
474    let mut collector = Collector::new(part);
475    collector.walk(document.root(), &mut Vec::new(), None);
476    let ranges = collector
477        .paragraphs
478        .iter()
479        .map(|paragraph| paragraph.text_start..paragraph.text_end)
480        .collect();
481    (collector.text, ranges)
482}
483
484/// What a paragraph turned out to be.
485enum ParagraphClass {
486    /// A structural tag that must be matched with its pair.
487    Tag(Tag),
488    /// Inline content.
489    Inline(Vec<AstNode>),
490    /// Whitespace only.
491    Empty,
492}
493
494fn classify_paragraph(
495    text: &str,
496    path: &[usize],
497    text_start: usize,
498    part: &str,
499) -> Result<ParagraphClass, BindingError> {
500    let trimmed = text.trim();
501    if trimmed.is_empty() {
502        return Ok(ParagraphClass::Empty);
503    }
504
505    let lead = text.len() - text.trim_start().len();
506    let tags = scan_tags(trimmed).map_err(|offset| BindingError::Syntax {
507        part: part.to_owned(),
508        message: format!("unclosed block tag at byte {}", text_start + lead + offset),
509    })?;
510
511    if let Some(tag_range) = tags.first()
512        && tags.len() == 1
513        && tag_range.start == 0
514        && tag_range.end == trimmed.len()
515    {
516        let tag = parse_tag(tag_range, trimmed, text_start + lead, part)?;
517        return Ok(ParagraphClass::Tag(tag));
518    }
519
520    match parse_covered(text) {
521        Ok(nodes) => Ok(ParagraphClass::Inline(nodes)),
522        Err(message) => {
523            let absolute: Vec<TextSpan> = tags
524                .iter()
525                .map(|tag| text_start + lead + tag.start..text_start + lead + tag.end)
526                .collect();
527            match absolute.as_slice() {
528                [] => Err(BindingError::Syntax {
529                    part: part.to_owned(),
530                    message: format!("in paragraph {path:?}: {message}"),
531                }),
532                [first] => {
533                    // A single structural tag with other text around it. If the
534                    // tag itself is unknown the parser message is the real cause.
535                    if let Some(tag_range) = tags.first() {
536                        parse_tag(tag_range, trimmed, text_start + lead, part)?;
537                    }
538                    Err(BindingError::TagSharesContainer {
539                        part: part.to_owned(),
540                        container: "paragraph",
541                        span: first.clone(),
542                    })
543                }
544                [first, second, ..] => Err(BindingError::MultipleTagsInBlock {
545                    part: part.to_owned(),
546                    path: path.to_vec(),
547                    first: first.clone(),
548                    second: second.clone(),
549                }),
550            }
551        }
552    }
553}
554
555/// Collect the marker sites for paragraphs and rows in document order.
556fn marker_sites(
557    paragraphs: &[BoundParagraph],
558    rows: &[BoundRow],
559    text: &str,
560    part: &str,
561) -> Result<Vec<TagSite>, BindingError> {
562    // A row is a marker row when its whole text is one block tag.
563    let mut row_tags: Vec<Option<(Tag, TextSpan, usize)>> = vec![None; rows.len()];
564    for (index, row) in rows.iter().enumerate() {
565        let Some(row_text) = text.get(row.text_start..row.text_end) else {
566            continue;
567        };
568        let trimmed = row_text.trim();
569        if trimmed.is_empty() {
570            continue;
571        }
572        let lead = row_text.len() - row_text.trim_start().len();
573        let tags = scan_tags(trimmed).map_err(|offset| BindingError::Syntax {
574            part: part.to_owned(),
575            message: format!(
576                "unclosed block tag at byte {}",
577                row.text_start + lead + offset
578            ),
579        })?;
580        let Some(tag_range) = tags.first() else {
581            continue;
582        };
583        if tags.len() != 1 || tag_range.start != 0 || tag_range.end != trimmed.len() {
584            continue;
585        }
586        let start = row.text_start + lead;
587        let tag = parse_tag(tag_range, trimmed, start, part)?;
588        let span = start..start + trimmed.len();
589        let paragraph = paragraphs
590            .iter()
591            .position(|paragraph| paragraph.text_start <= start && start < paragraph.text_end)
592            .or_else(|| {
593                paragraphs
594                    .iter()
595                    .position(|paragraph| paragraph.text_start == start)
596            })
597            .ok_or_else(|| BindingError::Syntax {
598                part: part.to_owned(),
599                message: format!("marker row at byte {start} has no paragraph"),
600            })?;
601        if let Some(slot) = row_tags.get_mut(index) {
602            *slot = Some((tag, span, paragraph));
603        }
604    }
605
606    let mut emitted_rows = vec![false; rows.len()];
607    let mut sites = Vec::new();
608
609    for (index, paragraph) in paragraphs.iter().enumerate() {
610        if let Some(row_index) = paragraph.enclosing_row
611            && let Some((tag, span, marker_paragraph)) =
612                row_tags.get(row_index).and_then(Option::as_ref)
613        {
614            let emitted = emitted_rows.get(row_index).copied().unwrap_or(true);
615            let Some(row) = rows.get(row_index) else {
616                continue;
617            };
618            if *marker_paragraph == index && !emitted {
619                if let Some(flag) = emitted_rows.get_mut(row_index) {
620                    *flag = true;
621                }
622                sites.push(TagSite {
623                    paragraph: index,
624                    path: row.path.clone(),
625                    index: sibling_index(&row.path),
626                    scope: Scope::Rows(row.table_path.clone()),
627                    span: span.clone(),
628                    tag: tag.clone(),
629                });
630            }
631            continue;
632        }
633
634        match classify_paragraph(
635            paragraph.text(),
636            &paragraph.path,
637            paragraph.text_start,
638            part,
639        )? {
640            ParagraphClass::Tag(tag) => sites.push(TagSite {
641                paragraph: index,
642                path: paragraph.path.clone(),
643                index: sibling_index(&paragraph.path),
644                scope: Scope::Blocks(parent(&paragraph.path)),
645                span: paragraph.text_start..paragraph.text_end,
646                tag,
647            }),
648            ParagraphClass::Inline(_) | ParagraphClass::Empty => {}
649        }
650    }
651
652    Ok(sites)
653}
654
655/// Match the marker sites into a block tree.
656fn match_blocks(
657    sites: &[TagSite],
658    containers: &[ContainerInfo],
659    part: &str,
660) -> Result<Vec<Block>, BindingError> {
661    struct Open {
662        tag: Tag,
663        site: TagSite,
664        elif_sites: Vec<TagSite>,
665        else_site: Option<TagSite>,
666        children: Vec<Block>,
667    }
668
669    let mut stack: Vec<Open> = Vec::new();
670    let mut roots: Vec<Block> = Vec::new();
671
672    for site in sites {
673        if site.tag.is_open() {
674            stack.push(Open {
675                tag: site.tag.clone(),
676                site: site.clone(),
677                elif_sites: Vec::new(),
678                else_site: None,
679                children: Vec::new(),
680            });
681            continue;
682        }
683
684        if let Tag::Elif(_) = site.tag {
685            let Some(open) = stack.last_mut() else {
686                return Err(BindingError::UnexpectedTag {
687                    part: part.to_owned(),
688                    span: site.span.clone(),
689                });
690            };
691            if !matches!(open.tag, Tag::IfStart(_)) {
692                return Err(BindingError::MismatchedBlock {
693                    part: part.to_owned(),
694                    open: open.site.span.clone(),
695                    close: site.span.clone(),
696                });
697            }
698            if let Some(else_site) = &open.else_site {
699                return Err(BindingError::MultipleTagsInBlock {
700                    part: part.to_owned(),
701                    path: open.site.path.clone(),
702                    first: else_site.span.clone(),
703                    second: site.span.clone(),
704                });
705            }
706            open.elif_sites.push(site.clone());
707            continue;
708        }
709
710        if matches!(site.tag, Tag::Else) {
711            let Some(open) = stack.last_mut() else {
712                return Err(BindingError::UnexpectedTag {
713                    part: part.to_owned(),
714                    span: site.span.clone(),
715                });
716            };
717            if !matches!(open.tag, Tag::IfStart(_)) {
718                return Err(BindingError::MismatchedBlock {
719                    part: part.to_owned(),
720                    open: open.site.span.clone(),
721                    close: site.span.clone(),
722                });
723            }
724            if open.else_site.is_some() {
725                return Err(BindingError::MultipleTagsInBlock {
726                    part: part.to_owned(),
727                    path: open.site.path.clone(),
728                    first: open
729                        .else_site
730                        .as_ref()
731                        .map(|s| s.span.clone())
732                        .unwrap_or_default(),
733                    second: site.span.clone(),
734                });
735            }
736            open.else_site = Some(site.clone());
737            continue;
738        }
739
740        let Some(open) = stack.pop() else {
741            return Err(BindingError::UnexpectedTag {
742                part: part.to_owned(),
743                span: site.span.clone(),
744            });
745        };
746
747        if !site.tag.closes(&open.tag) {
748            return Err(BindingError::MismatchedBlock {
749                part: part.to_owned(),
750                open: open.site.span.clone(),
751                close: site.span.clone(),
752            });
753        }
754
755        if open.site.scope != site.scope {
756            return Err(BindingError::BodyCrossesContainer {
757                part: part.to_owned(),
758                open: scope_path(&open.site.scope),
759                close: scope_path(&site.scope),
760            });
761        }
762
763        let first_separator = open
764            .elif_sites
765            .first()
766            .map(|site| site.index)
767            .or_else(|| open.else_site.as_ref().map(|site| site.index));
768        let then_body = open.site.index + 1..first_separator.unwrap_or(site.index);
769        let else_body = open
770            .else_site
771            .as_ref()
772            .map(|else_site| else_site.index + 1..site.index);
773
774        let kind = match &open.tag {
775            Tag::IfStart(condition) => BlockKind::Conditional {
776                condition: condition.clone(),
777                elifs: open
778                    .elif_sites
779                    .iter()
780                    .filter_map(|site| match &site.tag {
781                        Tag::Elif(condition) => Some(condition.clone()),
782                        _ => None,
783                    })
784                    .collect(),
785                has_else: open.else_site.is_some(),
786            },
787            Tag::ForStart { item, iterable } => {
788                if let Scope::Blocks(container) = &open.site.scope
789                    && let Some(info) = containers.iter().find(|info| &info.path == container)
790                {
791                    let wraps_table = then_body
792                        .clone()
793                        .any(|index| info.tables.get(index).copied().unwrap_or(false));
794                    if wraps_table {
795                        return Err(BindingError::LoopWrapsTable {
796                            part: part.to_owned(),
797                            span: open.site.span.clone(),
798                        });
799                    }
800                }
801                BlockKind::Loop {
802                    item: item.clone(),
803                    iterable: iterable.clone(),
804                }
805            }
806            Tag::Elif(_) | Tag::Else | Tag::IfEnd | Tag::ForEnd => {
807                return Err(BindingError::UnexpectedTag {
808                    part: part.to_owned(),
809                    span: site.span.clone(),
810                });
811            }
812        };
813
814        let block = Block {
815            kind,
816            scope: open.site.scope.clone(),
817            open: open.site,
818            close: site.clone(),
819            elif_sites: open.elif_sites,
820            else_site: open.else_site,
821            then_body,
822            else_body,
823            children: open.children,
824        };
825
826        match stack.last_mut() {
827            Some(parent) => parent.children.push(block),
828            None => roots.push(block),
829        }
830    }
831
832    if let Some(open) = stack.pop() {
833        return Err(BindingError::UnclosedBlock {
834            part: part.to_owned(),
835            span: open.site.span.clone(),
836        });
837    }
838
839    Ok(roots)
840}
841
842/// Parse the paragraphs that hold no structural tag.
843fn collect_inline(
844    paragraphs: &[BoundParagraph],
845    rows: &[BoundRow],
846    sites: &[TagSite],
847    part: &str,
848) -> Result<Vec<InlineContent>, BindingError> {
849    let mut marker_paragraphs = vec![false; paragraphs.len()];
850    for site in sites {
851        if let Some(flag) = marker_paragraphs.get_mut(site.paragraph) {
852            *flag = true;
853        }
854        if let Scope::Rows(_) = site.scope
855            && let Some(row_index) = rows.iter().position(|row| row.path == site.path)
856        {
857            for (index, paragraph) in paragraphs.iter().enumerate() {
858                if paragraph.enclosing_row == Some(row_index)
859                    && let Some(flag) = marker_paragraphs.get_mut(index)
860                {
861                    *flag = true;
862                }
863            }
864        }
865    }
866
867    let mut inline = Vec::new();
868    for (index, paragraph) in paragraphs.iter().enumerate() {
869        if marker_paragraphs.get(index).copied().unwrap_or(false) {
870            continue;
871        }
872        let text = paragraph.text();
873        if text.trim().is_empty() {
874            continue;
875        }
876        let nodes = parse_covered(text).map_err(|message| BindingError::Syntax {
877            part: part.to_owned(),
878            message: format!("in paragraph {:?}: {message}", paragraph.path),
879        })?;
880
881        if contains_for(&nodes) && paragraph.enclosing_row.is_none() {
882            return Err(BindingError::UnsupportedInlineLoop {
883                part: part.to_owned(),
884                path: paragraph.path.clone(),
885            });
886        }
887
888        inline.push(InlineContent {
889            paragraph: index,
890            nodes,
891        });
892    }
893
894    Ok(inline)
895}
896
897fn contains_for(nodes: &[AstNode]) -> bool {
898    nodes.iter().any(|node| match node {
899        AstNode::For(_) => true,
900        AstNode::If(if_node) => {
901            contains_for(&if_node.then_branch)
902                || if_node
903                    .else_branch
904                    .as_ref()
905                    .is_some_and(|branch| contains_for(branch))
906        }
907        _ => false,
908    })
909}
910
911fn sibling_index(path: &[usize]) -> usize {
912    path.last().copied().unwrap_or(0)
913}
914
915fn parent(path: &[usize]) -> Vec<usize> {
916    let mut parent = path.to_vec();
917    parent.pop();
918    parent
919}
920
921fn scope_path(scope: &Scope) -> Vec<usize> {
922    match scope {
923        Scope::Blocks(path) | Scope::Rows(path) => path.clone(),
924    }
925}
926
927fn contains(start: usize, end: usize, offset: usize) -> bool {
928    if start == end {
929        start == offset
930    } else {
931        start <= offset && offset < end
932    }
933}
934
935fn covered(start: usize, end: usize, range: &TextSpan) -> bool {
936    if start == end {
937        range.start <= start && (start < range.end || start == range.start)
938    } else {
939        range.start <= start && end <= range.end
940    }
941}
942
943/// Parse a whole string, rejecting trailing input the parser skipped.
944fn parse_covered(text: &str) -> Result<Vec<AstNode>, String> {
945    let nodes = crate::syntax::parse_template(text).map_err(|error| error.to_string())?;
946    let mut cursor = 0;
947    for node in &nodes {
948        let span = node.span();
949        if span.start != cursor {
950            return Err(format!("unexpected template syntax at byte {cursor}"));
951        }
952        cursor = span.end;
953    }
954    if cursor != text.len() {
955        return Err(format!("unexpected template syntax at byte {cursor}"));
956    }
957    Ok(nodes)
958}
959
960/// A raw block tag in a string.
961struct RawTag {
962    start: usize,
963    end: usize,
964    inner: Range<usize>,
965}
966
967/// Find every `{% ... %}` tag in a string.
968///
969/// Returns the offset of an unterminated tag.
970fn scan_tags(text: &str) -> Result<Vec<RawTag>, usize> {
971    let mut tags = Vec::new();
972    let mut from = 0;
973
974    while let Some(relative) = text[from..].find("{%") {
975        let start = from + relative;
976        let Some(close) = text[start + 2..].find("%}") else {
977            return Err(start);
978        };
979        let end = start + 2 + close + 2;
980        tags.push(RawTag {
981            start,
982            end,
983            inner: start + 2..end - 2,
984        });
985        from = end;
986        if from >= text.len() {
987            break;
988        }
989    }
990
991    Ok(tags)
992}
993
994/// Parse one raw tag.
995fn parse_tag(raw: &RawTag, text: &str, offset: usize, part: &str) -> Result<Tag, BindingError> {
996    let inner = text[raw.inner.clone()].trim();
997
998    let unexpected = |part: &str, offset: usize, raw: &RawTag| BindingError::UnexpectedTag {
999        part: part.to_owned(),
1000        span: offset + raw.start..offset + raw.end,
1001    };
1002
1003    if inner == "else" {
1004        return Ok(Tag::Else);
1005    }
1006    if inner == "endif" {
1007        return Ok(Tag::IfEnd);
1008    }
1009    if inner == "endfor" {
1010        return Ok(Tag::ForEnd);
1011    }
1012
1013    if let Some(rest) = inner.strip_prefix("if")
1014        && rest.starts_with(char::is_whitespace)
1015    {
1016        let expression = parse_expression(rest.trim()).map_err(|error| BindingError::Syntax {
1017            part: part.to_owned(),
1018            message: format!("in `{{% {inner} %}}`: {error}"),
1019        })?;
1020        return Ok(Tag::IfStart(expression));
1021    }
1022
1023    if let Some(rest) = inner.strip_prefix("elif")
1024        && rest.starts_with(char::is_whitespace)
1025    {
1026        let expression = parse_expression(rest.trim()).map_err(|error| BindingError::Syntax {
1027            part: part.to_owned(),
1028            message: format!("in `{{% {inner} %}}`: {error}"),
1029        })?;
1030        return Ok(Tag::Elif(expression));
1031    }
1032
1033    if let Some(rest) = inner.strip_prefix("for")
1034        && rest.starts_with(char::is_whitespace)
1035    {
1036        let body = rest.trim();
1037        let Some((item, iterable)) = body.split_once(" in ") else {
1038            return Err(unexpected(part, offset, raw));
1039        };
1040        let item = item.trim();
1041        if !is_identifier(item) {
1042            return Err(unexpected(part, offset, raw));
1043        }
1044        let iterable = parse_expression(iterable.trim()).map_err(|error| BindingError::Syntax {
1045            part: part.to_owned(),
1046            message: format!("in `{{% {inner} %}}`: {error}"),
1047        })?;
1048        return Ok(Tag::ForStart {
1049            item: item.to_owned(),
1050            iterable,
1051        });
1052    }
1053
1054    Err(unexpected(part, offset, raw))
1055}
1056
1057fn is_identifier(value: &str) -> bool {
1058    let mut chars = value.chars();
1059    match chars.next() {
1060        Some(first) if first.is_alphabetic() || first == '_' => {
1061            chars.all(|c| c.is_alphanumeric() || c == '_')
1062        }
1063        _ => false,
1064    }
1065}
1066
1067fn delimiter_offset(text: &str) -> Option<usize> {
1068    let brace = text.find("{{");
1069    let block = text.find("{%");
1070    match (brace, block) {
1071        (Some(left), Some(right)) => Some(left.min(right)),
1072        (Some(index), None) | (None, Some(index)) => Some(index),
1073        (None, None) => None,
1074    }
1075}
1076
1077/// The roles of the children of a block container.
1078struct ContainerInfo {
1079    path: Vec<usize>,
1080    tables: Vec<bool>,
1081}
1082
1083struct Collector {
1084    part: String,
1085    text: String,
1086    paragraphs: Vec<BoundParagraph>,
1087    rows: Vec<BoundRow>,
1088    containers: Vec<ContainerInfo>,
1089    error: Option<BindingError>,
1090}
1091
1092impl Collector {
1093    fn new(part: &str) -> Self {
1094        Self {
1095            part: part.to_owned(),
1096            text: String::new(),
1097            paragraphs: Vec::new(),
1098            rows: Vec::new(),
1099            containers: Vec::new(),
1100            error: None,
1101        }
1102    }
1103
1104    fn walk(&mut self, element: &Element, path: &mut Vec<usize>, row: Option<usize>) {
1105        if self.error.is_some() {
1106            return;
1107        }
1108
1109        if element.role() == Role::Opaque {
1110            if is_skipped_opaque(element.name()) {
1111                return;
1112            }
1113            let text = element.all_text();
1114            if let Some(offset) = delimiter_offset(&text) {
1115                self.error = Some(BindingError::TemplateInOpaqueElement {
1116                    part: self.part.clone(),
1117                    element: element.name().to_owned(),
1118                    offset,
1119                });
1120            }
1121            return;
1122        }
1123
1124        if matches!(
1125            element.role(),
1126            Role::Document | Role::Body | Role::Cell | Role::BlockContainer
1127        ) {
1128            self.containers.push(ContainerInfo {
1129                path: path.clone(),
1130                tables: element
1131                    .children()
1132                    .iter()
1133                    .map(|child| match child {
1134                        Node::Element(child) => child.role() == Role::Table,
1135                        _ => false,
1136                    })
1137                    .collect(),
1138            });
1139        }
1140
1141        let row_index = if element.role() == Role::Row {
1142            let index = self.rows.len();
1143            self.rows.push(BoundRow {
1144                path: path.clone(),
1145                table_path: parent(path),
1146                text_start: self.text.len(),
1147                text_end: self.text.len(),
1148                first_paragraph: self.paragraphs.len(),
1149            });
1150            Some(index)
1151        } else {
1152            row
1153        };
1154
1155        if element.role() == Role::Paragraph {
1156            let projection = project(element);
1157            let text_start = self.text.len();
1158            self.text.push_str(projection.text());
1159            let text_end = self.text.len();
1160            self.paragraphs.push(BoundParagraph {
1161                path: path.clone(),
1162                text_start,
1163                text_end,
1164                enclosing_row: row_index,
1165                projection,
1166            });
1167        }
1168
1169        for (index, child) in element.children().iter().enumerate() {
1170            if let Node::Element(child) = child {
1171                path.push(index);
1172                self.walk(child, path, row_index);
1173                path.pop();
1174            }
1175        }
1176
1177        if let Some(index) = row_index
1178            && element.role() == Role::Row
1179            && let Some(row) = self.rows.get_mut(index)
1180        {
1181            row.text_end = self.text.len();
1182        }
1183    }
1184}
1185
1186/// Elements whose text is not rendered and must not be scanned.
1187fn is_skipped_opaque(name: &str) -> bool {
1188    let local = name.rsplit(':').next().unwrap_or(name);
1189    matches!(local, "delText" | "instrText")
1190}
1191
1192#[cfg(test)]
1193mod tests {
1194    #![allow(
1195        clippy::unwrap_used,
1196        clippy::expect_used,
1197        clippy::panic,
1198        clippy::indexing_slicing
1199    )]
1200
1201    use super::*;
1202    use crate::domain::document::TextNode;
1203
1204    fn element(name: &str, role: Role, children: Vec<Node>) -> Element {
1205        Element::new(
1206            name.to_owned(),
1207            role,
1208            format!("<{name}>").into_bytes(),
1209            format!("</{name}>").into_bytes(),
1210            false,
1211            children,
1212        )
1213    }
1214
1215    fn text(value: &str) -> Node {
1216        Node::Text(TextNode::original(
1217            value.as_bytes().to_vec(),
1218            value.to_owned(),
1219        ))
1220    }
1221
1222    fn run(value: &str) -> Node {
1223        Node::Element(element(
1224            "w:r",
1225            Role::Run,
1226            vec![Node::Element(element("w:t", Role::Text, vec![text(value)]))],
1227        ))
1228    }
1229
1230    fn paragraph(value: &str) -> Node {
1231        Node::Element(element("w:p", Role::Paragraph, vec![run(value)]))
1232    }
1233
1234    fn paragraph_runs(values: &[&str]) -> Node {
1235        Node::Element(element(
1236            "w:p",
1237            Role::Paragraph,
1238            values.iter().map(|value| run(value)).collect(),
1239        ))
1240    }
1241
1242    fn cell(paragraphs: Vec<Node>) -> Node {
1243        Node::Element(element("w:tc", Role::Cell, paragraphs))
1244    }
1245
1246    fn row(cells: Vec<Node>) -> Node {
1247        Node::Element(element("w:tr", Role::Row, cells))
1248    }
1249
1250    fn table(rows: Vec<Node>) -> Node {
1251        Node::Element(element("w:tbl", Role::Table, rows))
1252    }
1253
1254    fn document(children: Vec<Node>) -> Document {
1255        let body = element("w:body", Role::Body, children);
1256        let root = element("w:document", Role::Document, vec![Node::Element(body)]);
1257        Document::new(Vec::new(), root, Vec::new(), "w".to_owned())
1258    }
1259
1260    fn bind_document(children: Vec<Node>) -> Result<BoundTemplate, BindingError> {
1261        bind(&document(children), "word/document.xml")
1262    }
1263
1264    #[test]
1265    fn binds_paragraphs_in_document_order() {
1266        let bound = bind_document(vec![paragraph("Hello "), paragraph("{{name}}")]).unwrap();
1267        assert_eq!(bound.paragraphs().len(), 2);
1268        assert_eq!(bound.text(), "Hello {{name}}");
1269        assert_eq!(bound.inline().len(), 2);
1270    }
1271
1272    #[test]
1273    fn a_variable_resolves_to_text_targets() {
1274        let bound = bind_document(vec![paragraph_runs(&["{{user.", "name}}"])]).unwrap();
1275        let content = &bound.inline()[0];
1276        let AstNode::Variable(variable) = &content.nodes[0] else {
1277            panic!("expected a variable");
1278        };
1279        let slices = bound
1280            .resolve_inline(content.paragraph, &(variable.span.start..variable.span.end))
1281            .unwrap();
1282        assert_eq!(slices.len(), 2);
1283        assert_eq!(slices[0].start, 0);
1284        assert_eq!(slices[1].end, 6);
1285    }
1286
1287    #[test]
1288    fn binds_a_block_loop_across_paragraphs() {
1289        let bound = bind_document(vec![
1290            paragraph("{% for item in items %}"),
1291            paragraph("{{item.name}}"),
1292            paragraph("{% endfor %}"),
1293        ])
1294        .unwrap();
1295        assert_eq!(bound.blocks().len(), 1);
1296        let block = &bound.blocks()[0];
1297        assert!(matches!(block.kind, BlockKind::Loop { .. }));
1298        assert_eq!(block.then_body, 1..2);
1299        assert_eq!(bound.inline().len(), 1);
1300        assert_eq!(
1301            bound.paragraphs()[bound.inline()[0].paragraph].text(),
1302            "{{item.name}}"
1303        );
1304    }
1305
1306    #[test]
1307    fn binds_a_block_conditional_with_branches() {
1308        let bound = bind_document(vec![
1309            paragraph("{% if admin %}"),
1310            paragraph("yes"),
1311            paragraph("{% else %}"),
1312            paragraph("no"),
1313            paragraph("{% endif %}"),
1314        ])
1315        .unwrap();
1316        let block = &bound.blocks()[0];
1317        assert!(matches!(
1318            block.kind,
1319            BlockKind::Conditional { has_else: true, .. }
1320        ));
1321        assert_eq!(block.then_body, 1..2);
1322        assert_eq!(block.else_body, Some(3..4));
1323    }
1324
1325    #[test]
1326    fn binds_a_row_loop() {
1327        let bound = bind_document(vec![table(vec![
1328            row(vec![cell(vec![paragraph("{% for item in items %}")])]),
1329            row(vec![cell(vec![paragraph("{{item.name}}")])]),
1330            row(vec![cell(vec![paragraph("{% endfor %}")])]),
1331        ])])
1332        .unwrap();
1333        assert_eq!(bound.blocks().len(), 1);
1334        let block = &bound.blocks()[0];
1335        assert!(matches!(block.scope, Scope::Rows(_)));
1336        assert_eq!(block.then_body, 1..2);
1337        assert_eq!(bound.rows().len(), 3);
1338    }
1339
1340    #[test]
1341    fn binds_an_inline_conditional() {
1342        let bound = bind_document(vec![paragraph("{% if a %}x{% endif %}")]).unwrap();
1343        assert!(bound.blocks().is_empty());
1344        assert_eq!(bound.inline().len(), 1);
1345        assert!(matches!(bound.inline()[0].nodes[0], AstNode::If(_)));
1346    }
1347
1348    #[test]
1349    fn a_tag_sharing_its_paragraph_is_rejected() {
1350        let error = bind_document(vec![paragraph("{% endif %} trailing")]).unwrap_err();
1351        assert!(matches!(error, BindingError::TagSharesContainer { .. }));
1352    }
1353
1354    #[test]
1355    fn a_body_that_crosses_a_container_is_rejected() {
1356        let error = bind_document(vec![
1357            paragraph("{% for item in items %}"),
1358            table(vec![row(vec![cell(vec![paragraph("{% endfor %}")])])]),
1359        ])
1360        .unwrap_err();
1361        assert!(matches!(error, BindingError::BodyCrossesContainer { .. }));
1362    }
1363
1364    #[test]
1365    fn a_loop_wrapping_a_table_is_rejected() {
1366        let error = bind_document(vec![
1367            paragraph("{% for item in items %}"),
1368            table(vec![row(vec![cell(vec![paragraph("{{item.name}}")])])]),
1369            paragraph("{% endfor %}"),
1370        ])
1371        .unwrap_err();
1372        assert!(matches!(error, BindingError::LoopWrapsTable { .. }));
1373    }
1374
1375    #[test]
1376    fn an_inline_loop_outside_a_row_is_rejected() {
1377        let error = bind_document(vec![paragraph(
1378            "{% for item in items %}{{item}}{% endfor %}",
1379        )])
1380        .unwrap_err();
1381        assert!(matches!(error, BindingError::UnsupportedInlineLoop { .. }));
1382    }
1383
1384    #[test]
1385    fn an_inline_loop_inside_a_row_binds() {
1386        let bound = bind_document(vec![table(vec![row(vec![cell(vec![paragraph(
1387            "{% for item in items %}{{item}}{% endfor %}",
1388        )])])])])
1389        .unwrap();
1390        assert!(bound.blocks().is_empty());
1391        assert_eq!(bound.inline().len(), 1);
1392        assert!(matches!(bound.inline()[0].nodes[0], AstNode::For(_)));
1393    }
1394
1395    #[test]
1396    fn two_structural_tags_in_one_block_are_rejected() {
1397        let error = bind_document(vec![paragraph("{% endif %}{% endfor %}")]).unwrap_err();
1398        assert!(matches!(error, BindingError::MultipleTagsInBlock { .. }));
1399    }
1400
1401    #[test]
1402    fn an_unclosed_block_is_rejected() {
1403        let error = bind_document(vec![paragraph("{% if a %}")]).unwrap_err();
1404        assert!(matches!(error, BindingError::UnclosedBlock { .. }));
1405    }
1406
1407    #[test]
1408    fn an_unexpected_tag_is_rejected() {
1409        let error = bind_document(vec![paragraph("{% endfor %}")]).unwrap_err();
1410        assert!(matches!(error, BindingError::UnexpectedTag { .. }));
1411    }
1412
1413    #[test]
1414    fn a_mismatched_pair_is_rejected() {
1415        let error =
1416            bind_document(vec![paragraph("{% if a %}"), paragraph("{% endfor %}")]).unwrap_err();
1417        assert!(matches!(error, BindingError::MismatchedBlock { .. }));
1418    }
1419
1420    #[test]
1421    fn template_inside_an_opaque_element_is_rejected() {
1422        let drawing = element(
1423            "w:drawing",
1424            Role::Opaque,
1425            vec![Node::Element(element(
1426                "a:t",
1427                Role::Opaque,
1428                vec![text("{{secret}}")],
1429            ))],
1430        );
1431        let error = bind_document(vec![Node::Element(drawing)]).unwrap_err();
1432        assert!(matches!(
1433            error,
1434            BindingError::TemplateInOpaqueElement { ref element, .. } if element == "w:drawing"
1435        ));
1436    }
1437
1438    #[test]
1439    fn deleted_text_is_skipped() {
1440        let deleted = element("w:delText", Role::Opaque, vec![text("{{gone}}")]);
1441        let bound = bind_document(vec![
1442            paragraph("kept"),
1443            Node::Element(element("w:r", Role::Run, vec![Node::Element(deleted)])),
1444        ])
1445        .unwrap();
1446        assert_eq!(bound.text(), "kept");
1447    }
1448
1449    #[test]
1450    fn maps_offsets_to_paragraphs() {
1451        let bound = bind_document(vec![paragraph("abc"), paragraph("def")]).unwrap();
1452        assert_eq!(bound.paragraph_at(0), Some(0));
1453        assert_eq!(bound.paragraph_at(2), Some(0));
1454        assert_eq!(bound.paragraph_at(3), Some(1));
1455        assert_eq!(bound.paragraph_at(5), Some(1));
1456        assert_eq!(bound.paragraph_at(6), None);
1457    }
1458
1459    #[test]
1460    fn reports_paragraphs_fully_inside_a_range() {
1461        let bound = bind_document(vec![
1462            paragraph("{% for x in xs %}"),
1463            paragraph("{{x}}"),
1464            paragraph("{% endfor %}"),
1465        ])
1466        .unwrap();
1467        assert_eq!(
1468            bound.paragraphs_in_range(0..bound.text().len()),
1469            vec![0, 1, 2]
1470        );
1471        assert_eq!(bound.paragraphs_in_range(0..1), Vec::<usize>::new());
1472    }
1473
1474    #[test]
1475    fn reports_unclosed_placeholders() {
1476        let error = bind_document(vec![paragraph("{{unclosed")]).unwrap_err();
1477        assert!(matches!(error, BindingError::Syntax { .. }));
1478    }
1479
1480    #[test]
1481    fn reports_unknown_tags() {
1482        let error = bind_document(vec![paragraph("{% wat %}")]).unwrap_err();
1483        assert!(matches!(error, BindingError::UnexpectedTag { .. }));
1484    }
1485}