flm_core/stdlib/features/annotations/cut.rs
1//! How an annotation is cut into cut parts at paragraph breaks and blocks:
2//! the element's implementation of the block-transparent aspect, and the
3//! continuation record every cut part carries.
4//!
5//! An annotation is *block-transparent*: its passage or remark is laid out as
6//! if it were written directly in the text around it
7//! ([block-transparent elements](crate::guide::concepts_overview#block-transparent-elements)).
8//! A blank line inside it is a paragraph break of the surrounding text, and
9//! the annotation continues into the next paragraph; a list inside it is a
10//! block of the surrounding text, still part of the annotation, and a
11//! displayed formula inside it stays in the inline content the annotation
12//! spans. Before any
13//! paragraph is built, the block-structure pass calls the element's
14//! [`BlockTransparent`] aspect, and the element replaces itself by **cut
15//! parts**: one node of its own element around each stretch of inline
16//! content between two paragraph breaks or blocks, and one around each
17//! block. The paragraph breaks are placed between the cut parts, so that the
18//! layout step that follows puts each stretch in its own paragraph. An
19//! annotation is never a block holding paragraphs.
20//!
21//! Every cut part carries an [`AnnotationPiece`] record (which cut it came
22//! from, its rank, how many cut parts the cut made). The lowering rules read
23//! it to put the initials on the first cut part only, and, on the text
24//! output, a comment's opening bracket on the first cut part and its closing
25//! bracket on the last.
26
27use std::sync::Arc;
28
29use techy::core::node::{BuildId, NodeRef};
30use techy::serialize::{DeserializeContext, DeserializeError, SerialValue};
31
32use crate::dump::session::PayloadReaders;
33use crate::lang::rewrites::blocks::{
34 argument_holds_blocks, run_holds_blocks, BlockCutter, BlockTransparent, CutItem, CutPart,
35 Cutting, StructureCx, StructureError,
36};
37use crate::lang::{Flm, PresPayload};
38use crate::model::aspects::{BlockRole, BlockRoleAspect, InlineSpacing};
39use crate::stdlib::backends::pres::payload::{bad, entries, field, map};
40use crate::stdlib::backends::pres::read::payload_of;
41
42use super::{AnnotationElement, ANNOTATION, TEXT_ARG};
43
44/// The continuation record a cut part of an annotation carries: which cut
45/// made it, its rank among the cut parts of that cut, and how many cut parts
46/// the cut made.
47///
48/// The block-structure pass cuts an annotation whose passage or remark
49/// crosses a paragraph break or holds a block into cut parts: one node of the
50/// annotation's element around each stretch of inline content, and one
51/// around each block ([the feature's documentation](super)). Each cut part
52/// carries this record as its payload
53/// ([`FlmNodeExt::payload`](crate::lang::FlmNodeExt::payload)); read it with
54/// [`payload_of`]`::<AnnotationPiece>(&node)`. An annotation that was not cut
55/// carries no record, and the lowering rules treat it as both the first and
56/// the last cut part.
57///
58/// The cut part with `index == 0` is the first: only it shows the initials.
59/// The cut part with `index + 1 == count` is the last. The record is plain
60/// data, serialized as `{cut, index, count}` and read back from that form by
61/// the reader that [`payload_readers`] registers under the element's name,
62/// so that a frozen tree holding cut parts can be read back from its
63/// serialized form.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
65pub struct AnnotationPiece {
66 /// The cut's number, unique within the tree, in the order in which the
67 /// block-structure pass reaches the annotations: an annotation before
68 /// those inside it.
69 pub cut: usize,
70 /// The cut part's rank among the cut parts of its cut, from zero.
71 pub index: usize,
72 /// How many cut parts the cut made.
73 pub count: usize,
74}
75
76impl AnnotationPiece {
77 /// Returns whether this is the first cut part of its cut.
78 pub fn is_first(&self) -> bool {
79 self.index == 0
80 }
81
82 /// Returns whether this is the last cut part of its cut.
83 pub fn is_last(&self) -> bool {
84 self.index + 1 == self.count
85 }
86
87 /// Rebuilds the record from its serialized form, `{cut, index, count}`.
88 ///
89 /// # Errors
90 ///
91 /// A [`DeserializeError`] that identifies the element when the value is
92 /// not a map holding the three fields as non-negative integers.
93 pub fn from_projection(value: &SerialValue) -> Result<AnnotationPiece, DeserializeError> {
94 let e = entries(ANNOTATION, value)?;
95 let number = |key: &str| match field(e, key) {
96 Some(SerialValue::Int(n)) if *n >= 0 => Ok(*n as usize),
97 Some(other) => Err(bad(ANNOTATION, format!("`{key}` must be a count, found {other:?}"))),
98 None => Err(bad(ANNOTATION, format!("`{key}` is missing"))),
99 };
100 Ok(AnnotationPiece { cut: number("cut")?, index: number("index")?, count: number("count")? })
101 }
102}
103
104impl PresPayload for AnnotationPiece {
105 fn project(&self) -> SerialValue {
106 let count = |n: usize| SerialValue::Int(n as i64);
107 map(vec![("cut", count(self.cut)), ("index", count(self.index)), ("count", count(self.count))])
108 }
109}
110
111/// Returns the payload readers of the feature: one, which reads back the
112/// continuation records of cut parts ([`AnnotationPiece`]), registered under
113/// the element's name [`ANNOTATION`].
114///
115/// A host that reads back a serialized frozen tree that may hold annotations
116/// registers these readers in the reading session
117/// ([`reader_with`](crate::dump::session::reader_with)), together with the
118/// readers of the presentation vocabulary when the tree is a lowered one.
119///
120/// # Examples
121///
122/// ```
123/// use flm_core::stdlib::features::annotations::{payload_readers, ANNOTATION};
124///
125/// let readers = payload_readers();
126/// assert!(readers.get(ANNOTATION).is_some());
127/// ```
128pub fn payload_readers() -> PayloadReaders {
129 let mut readers = PayloadReaders::new();
130 readers.register(ANNOTATION, |value: &SerialValue, _cx: &mut DeserializeContext<'_, Flm>| {
131 AnnotationPiece::from_projection(value).map(|record| Arc::new(record) as Arc<dyn PresPayload>)
132 });
133 readers
134}
135
136/// The position of the argument [`TEXT_ARG`] among an annotation's
137/// arguments: the first and only one.
138const TEXT_INDEX: usize = 0;
139
140/// An annotation is inline content where its argument is laid out as inline
141/// content, and a block where its argument is laid out as blocks: after the
142/// cut, that is a cut part around one block. Before the cut, an annotation
143/// holding a paragraph break is also a block, so that an annotation around
144/// it treats it as a place to cut.
145impl BlockRoleAspect for AnnotationElement {
146 fn block_role(&self, node: &NodeRef<'_, Flm>) -> BlockRole {
147 if argument_holds_blocks(node, TEXT_INDEX) {
148 BlockRole::Block
149 } else {
150 BlockRole::Inline(InlineSpacing::CONTENT)
151 }
152 }
153}
154
155/// One cut part to build, or an item passed through unchanged.
156enum Plan {
157 /// A cut part around these staged nodes: a cut part around a block when
158 /// the flag is set.
159 Piece(Vec<BuildId>, bool),
160 /// A paragraph-break marker, or a stretch of comments and whitespace
161 /// alone, passed through.
162 Through(CutItem),
163}
164
165/// The cut of an annotation. An annotation is left unchanged when its
166/// argument holds no paragraph break and no block, or when it is already a
167/// cut part. Otherwise it is cut into one cut part around each stretch of
168/// inline content and one around each block, with the paragraph-break markers
169/// passed through between them. A stretch of whitespace and source comments
170/// alone makes no cut part, so an annotation holding nothing but a paragraph
171/// break (`\phf{`, a blank line, `}`) is cut into no cut part and leaves
172/// nothing of itself, while `\phf{}`, which is not cut, is an annotation of
173/// empty content.
174impl BlockTransparent for AnnotationElement {
175 fn cut(
176 &self,
177 node: NodeRef<'_, Flm>,
178 cx: &mut StructureCx<'_>,
179 cutter: &mut dyn BlockCutter,
180 ) -> Result<Cutting, StructureError> {
181 // A piece is asked again — when a structured tree is structured once
182 // more, and a block piece's argument holds its block — and is left
183 // as it is, its record with it.
184 if payload_of::<AnnotationPiece>(&node).is_some() {
185 return Ok(Cutting::Default);
186 }
187 let run: Vec<NodeRef<'_, Flm>> =
188 node.argument_content_nodes(TEXT_INDEX).map(|content| content.iter().collect()).unwrap_or_default();
189 if !run_holds_blocks(&run) {
190 return Ok(Cutting::Default);
191 }
192 let cut = cutter.new_cut_number();
193 let mut plans = Vec::new();
194 let mut stretch = Vec::new();
195 for item in cutter.restage_and_classify(cx, &run)? {
196 match item {
197 CutItem::Inline(_) | CutItem::Blank(_) => stretch.push(item),
198 CutItem::Marker(_) => {
199 flush(&mut stretch, &mut plans);
200 plans.push(Plan::Through(item));
201 }
202 CutItem::Block(id) => {
203 flush(&mut stretch, &mut plans);
204 plans.push(Plan::Piece(vec![id], true));
205 }
206 }
207 }
208 flush(&mut stretch, &mut plans);
209 let count = plans.iter().filter(|plan| matches!(plan, Plan::Piece(..))).count();
210 let mut items = Vec::with_capacity(plans.len());
211 let mut index = 0;
212 for plan in plans {
213 match plan {
214 Plan::Through(item) => items.push(item),
215 Plan::Piece(content, block) => {
216 let record = Arc::new(AnnotationPiece { cut, index, count });
217 let part = vec![(CutPart::ArgumentNamed(TEXT_ARG.to_string()), content)];
218 let id = cutter.rebuild(cx, &node, part, Some(record))?;
219 items.push(if block { CutItem::Block(id) } else { CutItem::Inline(id) });
220 index += 1;
221 }
222 }
223 }
224 Ok(Cutting::Emit(items))
225 }
226}
227
228/// Ends the stretch of inline and blank items gathered so far: one cut part
229/// around it when it holds some inline content, otherwise its items passed
230/// through unchanged.
231fn flush(stretch: &mut Vec<CutItem>, plans: &mut Vec<Plan>) {
232 if stretch.iter().any(|item| matches!(item, CutItem::Inline(_))) {
233 plans.push(Plan::Piece(stretch.drain(..).map(CutItem::id).collect(), false));
234 } else {
235 plans.extend(stretch.drain(..).map(Plan::Through));
236 }
237}