flm_core/stdlib/features/floats/body.rs
1//! Reading a float's body: the three commands `\caption[alt=…]{…}`,
2//! `\label{…}` and `\nonumber`, the float's content, and whether the float
3//! type's numbering policy numbers the float.
4//!
5//! A float's body is read each time it is needed, and nothing read is stored.
6//! Two readers exist, for two uses:
7//!
8//! - [`float_fields`] reads the body and reports nothing. The float's reference
9//! point ([`FloatElement`]'s implementation of
10//! [`Referenceable`](crate::model::aspects::Referenceable)) is computed
11//! through it.
12//! - [`read_float`] reads the body through [`float_fields`] and reports, at the
13//! float being lowered, every problem of the body (the conditions of
14//! [`diagnostics`](super::diagnostics)), and which of the float type's
15//! content handlers accepted the content, or the refusals where none did.
16//! Every lowering rule of a float calls
17//! it, so a document gets the same diagnostics on every backend.
18//!
19//! # Where the commands are read
20//!
21//! The three commands are the elements of the float's scoped package
22//! [`FIELDS_PACKAGE`](super::FIELDS_PACKAGE). Each is inline content, so the
23//! block-structure pass ([`blocks`](crate::lang::rewrites::blocks)), which
24//! groups a body's inline content into paragraphs, places a command written
25//! on its own line in a paragraph. The reader therefore takes a command from two places: directly
26//! in the body, and directly in a paragraph that the block-structure pass
27//! built in the body.
28//!
29//! The **content** is every other direct child of the body, except source
30//! comments, whitespace (text made of whitespace alone, and the nodes that
31//! are whitespace, such as `~` and `\ `), and paragraph breaks. A paragraph
32//! that holds nothing but commands, whitespace and source comments is left out
33//! of the content as a whole; a paragraph that holds a command beside other
34//! content is one content node, and the float's rule leaves the command out
35//! when it lowers that paragraph.
36//!
37//! On the raw tree that the recomposed LaTeX reads (the frozen tree that the
38//! block-structure pass has not processed; [the raw
39//! tree](mod@crate::stdlib::backends::latex_recomposed::rules#the-raw-tree)), no
40//! paragraph is built: the commands and the content are the body's direct
41//! children, and the paragraph breaks among them are left out.
42//!
43//! A command written deeper, inside a group, a list or another construct, does
44//! not belong to the float: it reaches the lowering as a field node no
45//! construct read, which is reported as `flm.lowering.field-not-read`
46//! ([`FieldNotRead`](crate::stdlib::backends::lowering::error::FieldNotRead)).
47
48use techy::core::node::NodeRef;
49use techy::extract::parse_keyval_drop_annotations;
50
51use crate::core::lowering::{LowerError, Lowerer};
52use crate::lang::copy::{
53 ValueContent, ValuePiece, WrittenPiece, copy_pieces_into_value, key_value_pieces,
54};
55use crate::lang::guard::{GuardPolicy, on_worker_thread};
56use crate::lang::mint::field_name;
57use crate::lang::{Flm, FlmGroupType};
58use crate::model::aspects::ContentRef;
59use crate::lang::structural::PARBREAK;
60use crate::lang::text::{is_blank, is_space};
61use crate::model::element::{element_of, element_value};
62use crate::stdlib::features::numbering::COUNTERS;
63use crate::stdlib::features::refs::{self, ANCHORS, LABEL_FIELD};
64
65use super::config::{FloatNumbering, FloatType};
66use super::content::{Handlers, Verdict};
67use super::diagnostics::{
68 CaptionMissingValue, CaptionRepeated, CaptionRepeatedKey, CaptionUnknownKey, ContentRefused,
69 LabelWithoutRefs, NoNumbering, NonumberWithoutEffect,
70};
71use super::elements::FloatElement;
72use super::{ALT_KEY, CAPTION_FIELD, CAPTION_OPTIONS_ARG, CAPTION_TEXT_ARG, NONUMBER_FIELD};
73
74/// The commands and the content of a float's body, each list in document
75/// order, as [`float_body`] reads them. See the [module
76/// documentation](self) for which nodes go where.
77#[derive(Debug, Clone, Default)]
78pub struct FloatBody<'t> {
79 /// The content nodes: what the content handlers are given
80 /// ([`FloatContentHandler::admit`](super::FloatContentHandler::admit)) and
81 /// what the float's rule lowers as the float's content.
82 pub content: Vec<NodeRef<'t, Flm>>,
83 /// Every `\caption` node, in order; the first is the float's caption.
84 pub captions: Vec<NodeRef<'t, Flm>>,
85 /// Every `\nonumber` node, in order.
86 pub nonumbers: Vec<NodeRef<'t, Flm>>,
87 /// Every `\label` node, in order.
88 pub labels: Vec<NodeRef<'t, Flm>>,
89}
90
91/// Whether `node` is one of the float's three commands (`\caption`,
92/// `\label`, `\nonumber`): what the float's rules leave out of a paragraph
93/// they lower.
94pub(super) fn is_float_field(node: &NodeRef<'_, Flm>) -> bool {
95 field_name(node).is_some_and(|name| {
96 name == CAPTION_FIELD || name == NONUMBER_FIELD || name == LABEL_FIELD
97 })
98}
99
100/// Whether `node` is left out of a float's content: a source comment,
101/// whitespace ([`is_blank`]: text made of whitespace alone, or a node that is
102/// whitespace, such as `~` and `\ `), or a paragraph break (which is found in
103/// the body where the block-structure pass built no paragraph, as on the raw
104/// tree the recomposed LaTeX reads).
105pub(super) fn is_aside(node: &NodeRef<'_, Flm>) -> bool {
106 node.is_comment() || is_blank(node) || element_of(node).name.as_str() == PARBREAK
107}
108
109/// Whether `node` is a paragraph that the block-structure pass built.
110pub(super) fn is_paragraph(node: &NodeRef<'_, Flm>) -> bool {
111 node.group_type() == Some(FlmGroupType::Paragraph)
112}
113
114/// Returns the commands and the content of the body of the float `node`, as
115/// the [module documentation](self) describes. Returns an empty
116/// [`FloatBody`] for a node with no body. Reports nothing.
117// The fields are read from the body each time they are needed, as every
118// construct of the language reads its fields, rather than stored by a stage.
119pub fn float_body<'t>(node: &NodeRef<'t, Flm>) -> FloatBody<'t> {
120 let mut body = FloatBody::default();
121 let Some(children) = node.body() else { return body };
122 let file = |field: NodeRef<'t, Flm>, body: &mut FloatBody<'t>| {
123 match field_name(&field) {
124 Some(CAPTION_FIELD) => body.captions.push(field),
125 Some(NONUMBER_FIELD) => body.nonumbers.push(field),
126 _ => body.labels.push(field),
127 }
128 };
129 for child in children.iter() {
130 if is_aside(&child) {
131 continue;
132 }
133 if is_float_field(&child) {
134 file(child, &mut body);
135 continue;
136 }
137 if is_paragraph(&child) {
138 let mut holds_content = false;
139 for inner in child.children().iter() {
140 if is_float_field(&inner) {
141 file(inner, &mut body);
142 } else if !is_aside(&inner) {
143 holds_content = true;
144 }
145 }
146 if !holds_content {
147 continue;
148 }
149 }
150 body.content.push(child);
151 }
152 body
153}
154
155/// One problem of a caption's optional argument, in the order written.
156#[derive(Debug, Clone, PartialEq, Eq)]
157enum CaptionProblem {
158 /// A key other than `alt`, as written, or the whole argument as written
159 /// where it is not key-value pairs.
160 UnknownKey(String),
161 /// `alt` written with no value.
162 MissingValue,
163 /// `alt=` written a second time.
164 RepeatedKey,
165}
166
167/// A float's caption, read from its first `\caption` command
168/// ([`read_caption`]): the command's node, and the caption's alternative text
169/// where its optional argument gives one.
170#[derive(Debug, Clone)]
171pub struct Caption<'t> {
172 /// The `\caption` node.
173 pub node: NodeRef<'t, Flm>,
174 /// The caption's **alternative text**, which a reference to an
175 /// unnumbered float shows in place of the full caption: the value of
176 /// `alt=` as written in the document, as nodes of the optional argument
177 /// and as text cut from a run of characters that also holds the key.
178 /// `None` where the optional argument gives no `alt=` that can be read.
179 pub alt: Option<Vec<WrittenPiece<'t>>>,
180 /// The problems of the optional argument, in the order written.
181 problems: Vec<CaptionProblem>,
182}
183
184impl<'t> Caption<'t> {
185 /// Returns the caption's full content: the nodes of its mandatory
186 /// argument. Returns an empty list where the argument holds nothing.
187 pub fn content(&self) -> Vec<NodeRef<'t, Flm>> {
188 self.node
189 .argument_content_nodes_named(CAPTION_TEXT_ARG)
190 .ok()
191 .flatten()
192 .map(|nodes| nodes.iter().collect())
193 .unwrap_or_default()
194 }
195
196 /// Returns what a reference to the float shows where the float has no
197 /// number, as the content of its reference point
198 /// ([`RefPoint::content`](crate::model::aspects::RefPoint::content)):
199 ///
200 /// - where the optional argument gives an alternative text, a copy of it
201 /// in a synthesized value of its own
202 /// ([`ContentRef::Synthesized`]); `float`, the float node, gives the
203 /// position in the source of the parts of the copy that have none of
204 /// their own;
205 /// - otherwise, the caption's mandatory argument where it is written as
206 /// one group or one token, referred to by that node
207 /// ([`ContentRef::Node`]);
208 /// - `None` otherwise, and where the copy fails, which only content
209 /// nested deeper than the [recursion guard](crate::lang::guard) allows
210 /// can cause (the parse
211 /// refuses such content first).
212 pub fn shown_content(&self, float: &NodeRef<'t, Flm>) -> Option<ContentRef> {
213 if let Some(alt) = &self.alt {
214 let pieces: Vec<ValuePiece<'_, '_>> = alt.iter().map(WrittenPiece::as_value_piece).collect();
215 // A reference to the float shows the copy; the caption shows its
216 // full content where it stands.
217 return on_worker_thread(|| {
218 copy_pieces_into_value(&pieces, float, ValueContent::Shown, GuardPolicy::StackBudget)
219 })
220 .ok()?
221 .ok()
222 .map(ContentRef::Synthesized);
223 }
224 // The argument is written as one group, or as one token: that node
225 // holds the content by itself.
226 let region: Vec<NodeRef<'t, Flm>> = self
227 .node
228 .argument_nodes_named(CAPTION_TEXT_ARG)
229 .ok()
230 .flatten()
231 .map(|nodes| nodes.iter().filter(|node| !(node.is_comment() || is_blank(node))).collect())
232 .unwrap_or_default();
233 match region.as_slice() {
234 [one] => Some(ContentRef::Node(one.id())),
235 _ => None,
236 }
237 }
238}
239
240/// Reads the caption `node`, a `\caption` node: the `alt=` of its optional
241/// argument and the argument's problems. Reports nothing; [`read_float`]
242/// reports the problems.
243///
244/// The optional argument holds key-value pairs, read by techy's key-value
245/// reader ([`parse_keyval_drop_annotations`]), with the only key [`ALT_KEY`]
246/// (`alt`), whose value is content: `alt=Short`, `alt={Short, with a
247/// comma}`. An argument holding nothing but whitespace (`~` and `\ `
248/// included) and comments is read as if it were not written. These are
249/// recorded as problems: any other key; an argument that is not key-value
250/// pairs, or that holds no `=` at all (`\caption[Short]{…}` is read as the
251/// key `Short`); `alt` with no value; and a second `alt=`, the first being
252/// kept.
253pub fn read_caption<'t>(node: NodeRef<'t, Flm>) -> Caption<'t> {
254 let mut caption = Caption { node, alt: None, problems: Vec::new() };
255 let Some(content) = node.argument_content_nodes_named(CAPTION_OPTIONS_ARG).ok().flatten() else {
256 return caption;
257 };
258 if content.iter().all(|child| child.is_comment() || is_blank(&child)) {
259 return caption;
260 }
261 let Ok(keyvals) = parse_keyval_drop_annotations(content) else {
262 let written: String = content.iter().map(|node| node.span_content().to_string()).collect();
263 caption.problems.push(CaptionProblem::UnknownKey(written.trim_matches(is_space).to_string()));
264 return caption;
265 };
266 for entry in keyvals.iter() {
267 let key = entry.key();
268 if key.is_empty() {
269 continue;
270 }
271 if key != ALT_KEY {
272 caption.problems.push(CaptionProblem::UnknownKey(key.to_string()));
273 continue;
274 }
275 let Some(value) = entry.value() else {
276 caption.problems.push(CaptionProblem::MissingValue);
277 continue;
278 };
279 if caption.alt.is_some() {
280 caption.problems.push(CaptionProblem::RepeatedKey);
281 continue;
282 }
283 caption.alt = Some(key_value_pieces(&content, value));
284 }
285 caption
286}
287
288/// A float's body as [`float_fields`] reads it, without reporting anything:
289/// the float type, the commands and the content, the caption, and whether the
290/// type's numbering policy numbers the float.
291#[derive(Debug, Clone)]
292pub struct FloatFields<'t> {
293 /// The float's type.
294 pub float_type: &'t FloatType,
295 /// The body's commands and content.
296 pub body: FloatBody<'t>,
297 /// The float's caption, read from its first `\caption`. `None` where
298 /// the body holds no `\caption`.
299 pub caption: Option<Caption<'t>>,
300 /// Whether the type's numbering policy numbers the float, given its
301 /// commands ([`FloatNumbering::numbers`]): a float with at least one
302 /// `\label` counts as labeled, and a float with at least one `\nonumber`
303 /// as marked unnumbered. Whether the float is shown with a number also
304 /// depends on the output: without the numbering feature, the plain-text
305 /// and HTML outputs show it without a number ([`NoNumbering`]), while the
306 /// recomposed LaTeX still writes it as numbered and LaTeX numbers it.
307 pub numbered: bool,
308}
309
310/// Reads the body of the float `node` and reports nothing. Returns `None`
311/// for a node that is not a float (whose element does not carry a
312/// [`FloatElement`]).
313///
314/// The float's reference point is computed from what it returns;
315/// [`read_float`] calls it and reports the problems.
316pub fn float_fields<'t>(node: &NodeRef<'t, Flm>) -> Option<FloatFields<'t>> {
317 let value = element_value::<FloatElement>(node)?;
318 let body = float_body(node);
319 let caption = body.captions.first().map(|first| read_caption(*first));
320 let numbered = value.float_type.numbering.numbers(!body.labels.is_empty(), !body.nonumbers.is_empty());
321 Some(FloatFields { float_type: &value.float_type, body, caption, numbered })
322}
323
324/// A float as [`read_float`] reads it for a lowering rule: its body, and
325/// which of its type's content handlers accepted the content, or the
326/// refusals where none did.
327#[derive(Debug, Clone)]
328pub struct FloatReading<'t> {
329 /// The float's body.
330 pub fields: FloatFields<'t>,
331 /// The content handlers' verdict on the content.
332 pub verdict: Verdict,
333}
334
335/// Reads the float `node` for a lowering rule, as every rule lowering a float
336/// reads it, and reports through `lw` the problems of the float's body:
337///
338/// - each `\caption` after the first, an Error ([`CaptionRepeated`]) at that
339/// caption; the first is the float's caption;
340/// - the problems of the first caption's optional argument, each an Error at
341/// the caption: a key other than `alt` ([`CaptionUnknownKey`]), `alt` with
342/// no value ([`CaptionMissingValue`]), a second `alt=`
343/// ([`CaptionRepeatedKey`]);
344/// - each `\nonumber` that changes nothing, a Note
345/// ([`NonumberWithoutEffect`]) at it: in a float of a type that is never
346/// numbered, in a float without `\label` of a type numbered only when
347/// labeled, and each `\nonumber` after the first;
348/// - a `\label` when the references feature is not registered (the anchors
349/// table is absent), a Note ([`LabelWithoutRefs`]) at the first label;
350/// - a float that its policy numbers when the numbering feature is not
351/// registered (the counter table is absent), an Error ([`NoNumbering`]) at
352/// the float;
353/// - content that none of the type's content handlers accepts, an Error
354/// ([`ContentRefused`]) at the float. The message lists what each handler
355/// that a registered feature contributes would accept; where no handler the
356/// type lists is contributed, it says that none of the kinds of content the
357/// type accepts is available.
358///
359/// `handlers` are the content handlers of the registry, as the feature's
360/// rules hold them. The calling rule must declare optional reads of the
361/// counter table [`COUNTERS`] and of the anchors table [`ANCHORS`]
362/// ([`float_decl`](super::float_decl) declares both).
363///
364/// # Errors
365///
366/// [`LowerError`] for a node that is not a float; where the float has a
367/// `\label` and the calling rule did not declare a read of [`ANCHORS`]; and
368/// where the float's numbering policy numbers it and the calling rule did not
369/// declare a read of [`COUNTERS`].
370pub fn read_float<'t>(
371 node: &NodeRef<'t, Flm>,
372 handlers: &Handlers,
373 lw: &mut dyn Lowerer,
374) -> Result<FloatReading<'t>, LowerError> {
375 let fields = float_fields(node)
376 .ok_or_else(|| LowerError::structure("a float without its element's data"))?;
377 let float_type = fields.float_type;
378 let type_name = float_type.name.to_string();
379 for extra in fields.body.captions.iter().skip(1) {
380 lw.error(CaptionRepeated { float_type: type_name.clone() }, extra.span().clone());
381 }
382 if let Some(caption) = &fields.caption {
383 let span = caption.node.span().clone();
384 for problem in &caption.problems {
385 match problem {
386 CaptionProblem::UnknownKey(key) => {
387 lw.error(CaptionUnknownKey { key: key.clone() }, span.clone())
388 }
389 CaptionProblem::MissingValue => lw.error(CaptionMissingValue, span.clone()),
390 CaptionProblem::RepeatedKey => lw.error(CaptionRepeatedKey, span.clone()),
391 }
392 }
393 }
394 let labeled = !fields.body.labels.is_empty();
395 for (at, nonumber) in fields.body.nonumbers.iter().enumerate() {
396 let reason = match float_type.numbering {
397 FloatNumbering::Unnumbered => format!("a ‘{type_name}’ is never numbered"),
398 FloatNumbering::AutoNumbered if !labeled => {
399 format!("a ‘{type_name}’ without a ‘\\label’ is not numbered")
400 }
401 _ if at > 0 => String::from("it is already written in this float"),
402 _ => continue,
403 };
404 lw.note(NonumberWithoutEffect { reason }, nonumber.span().clone());
405 }
406 if let Some(first) = fields.body.labels.first() {
407 if lw.get(ANCHORS)?.is_none() {
408 lw.note(LabelWithoutRefs { float_type: type_name.clone() }, first.span().clone());
409 }
410 }
411 if fields.numbered && lw.get(COUNTERS)?.is_none() {
412 lw.error(NoNumbering { float_type: type_name.clone() }, node.span().clone());
413 }
414 let verdict = handlers.verdict(&float_type.handlers, &fields.body.content);
415 if let Verdict::Refused(refusals) = &verdict {
416 let admitted = if refusals.is_empty() {
417 let kinds: Vec<String> = float_type.handlers.iter().map(|kind| format!("‘{kind}’")).collect();
418 match kinds.as_slice() {
419 [one] => format!("content accepted by the missing content handler {one}"),
420 _ => format!(
421 "content accepted by one of the missing content handlers {}",
422 english_or(&kinds)
423 ),
424 }
425 } else {
426 english_or(refusals)
427 };
428 lw.error(ContentRefused { float_type: type_name, admitted }, node.span().clone());
429 }
430 Ok(FloatReading { fields, verdict })
431}
432
433/// Returns `items` joined as an English list with `or` and no serial comma: `a`,
434/// `a or b`, `a, b or c`.
435fn english_or(items: &[String]) -> String {
436 match items.split_last() {
437 None => String::new(),
438 Some((last, [])) => last.clone(),
439 Some((last, rest)) => format!("{} or {last}", rest.join(", ")),
440 }
441}
442
443/// Returns the labels written in the float's body, read as the references
444/// feature reads a run of `\label` nodes ([`refs::label_uses_in`]).
445pub(super) fn label_uses(fields: &FloatFields<'_>) -> Vec<refs::LabelUse> {
446 refs::label_uses_in(fields.body.labels.iter().copied())
447}
448
449#[cfg(test)]
450mod tests {
451 use super::english_or;
452
453 #[test]
454 fn the_admitted_contents_join_with_or() {
455 let items = |list: &[&str]| list.iter().map(|item| item.to_string()).collect::<Vec<_>>();
456 assert_eq!(english_or(&items(&["one image"])), "one image");
457 assert_eq!(english_or(&items(&["a", "b"])), "a or b");
458 assert_eq!(english_or(&items(&["a", "b", "c"])), "a, b or c");
459 }
460}