Skip to main content

flm_core/stdlib/features/math/
lines.rs

1//! Equation lines: the four commands an author writes inside a display-math
2//! environment's body (`\\`, `\label`, `\tag` and `\nonumber`), and the reader
3//! that splits such a body into lines.
4//!
5//! An equation line is one line of a display-math environment as its body reads
6//! between two `\\`: its mathematics, its labels, its tag and its no-number mark;
7//! each line is one reference point ([equation
8//! lines](crate::guide::concepts_overview#equation-lines)). An `align` body such
9//! as `a &= b \label{eq:first} \\ c &= d \nonumber` holds two lines. The
10//! [`math`](super) feature declares one reference point per line and numbers it
11//! from what [`equation_lines`] reads here; the lowering rules of the feature
12//! that processes mathematics write each line's tag or number, and, on the
13//! `latex-recomposed` backend, each line's labels.
14//!
15//! # The four commands
16//!
17//! | written | field name | what the line records |
18//! |---|---|---|
19//! | `\\`, `\\[1ex]` | [`LINEBREAK_COMMAND`] | the end of the line, and the optional spacing as written |
20//! | `\label{eq:name}` | [`LABEL_FIELD`](crate::stdlib::features::refs::LABEL_FIELD) | a label of the line |
21//! | `\tag{A}`, `\tag*{A}` | [`TAG_COMMAND`] | the tag's content as inline nodes, and whether the star was written |
22//! | `\nonumber` | [`NONUMBER_COMMAND`] | the line is not numbered |
23//!
24//! The four commands are declared in the scoped package
25//! ([`ScopedPackageDef`]) [`PACKAGE`] (`flm.math.lines`): a set of element
26//! declarations that can be written only inside the environment bodies and
27//! arguments whose declarations refer to the package by name ([scoped
28//! packages](crate::guide::concepts_overview#scoped-packages)). The bodies of the
29//! six display-math environments refer to it, and the declarations are for math
30//! mode only, so this module's declarations apply inside
31//! `\begin{align}…\end{align}` and the other five environments, and nowhere
32//! else. In inline mathematics `\(…\)` and in displayed mathematics `\[…\]`,
33//! `\\` and `\tag` are commands this module does not declare (under the
34//! [`math-passthrough`](crate::math_passthrough) feature,
35//! unknown commands kept as source); in text mode they mean what another feature
36//! declares there, if anything.
37//!
38//! All four are **fields**: macros that a construct reads as data rather than
39//! as content ([fields](crate::guide::concepts_overview#fields-data-a-construct-reads)). Each node
40//! carries an element named [`FIELD`](crate::lang::structural::FIELD) and is
41//! read by the command's name, and the environment's reader, [`equation_lines`],
42//! gives them their meaning. Where a command is written inside its line makes no
43//! difference to what the line records. The `\label` declared here is a
44//! separate declaration from the `\label` that a heading reads after its
45//! arguments, but it produces a field node of the same field name, so
46//! the references feature's reader of a label, [`label_use`](crate::stdlib::features::refs::label_use),
47//! reads it unchanged.
48//!
49//! The optional argument of `\\` must follow the command immediately: in
50//! `a \\ [b]` the `[b]` is content of the next line, not spacing. This keeps a
51//! bracketed expression at the start of a line from being read as spacing.
52//!
53//! `\nonumber` is the only way to write the no-number mark. `\notag`, which
54//! LaTeX's `amsmath` package also accepts, is not declared: inside a body it is
55//! an unknown command, kept as source in the line.
56//!
57//! The whitespace right after a command's name belongs to the command's node
58//! (see [macros](crate::guide::language_syntax#macros) in the syntax guide), so
59//! the newline after `\nonumber` is not part of the line's content. The name of
60//! `\\` is a single character that is not a letter, which takes no such
61//! whitespace, so the newline after it begins the next line's content.
62//!
63//! # Reading a body as lines
64//!
65//! [`equation_lines`] reads the direct children of an environment's body once
66//! and returns one [`EquationLine`] per line, in order:
67//!
68//! - A `\\` ends the line being read.
69//! - A `\label`, `\tag` or `\nonumber` is taken out of the content and recorded
70//!   on the line it is written in. A `\label` written on a line of its own before
71//!   the `\\` belongs to the line that `\\` ends; one written right after a `\\`
72//!   belongs to the next line. The whitespace around such a command stays in
73//!   the content; where the command stood on a line of its own, the LaTeX
74//!   writers keep a blank line from appearing through the `math` library's
75//!   newline rule ([`normalize_line_newlines`](super::latex::normalize_line_newlines)).
76//! - Everything else (mathematics, whitespace, comments, and nested environments
77//!   as a whole) is the line's [`content`](EquationLine::content), in order. The
78//!   nodes of a nested environment are not examined, so a `\\` inside a `cases`
79//!   or `matrix` environment nested in an `align` does not split the outer lines.
80//! - A body with no `\\` is one line.
81//! - A `\\` followed only by whitespace, blank lines and comments ends the last
82//!   line and begins no further one. It is not recorded (the last line's
83//!   [`linebreak`](EquationLine::linebreak) is `None`), and the whitespace and
84//!   comments after it are added to the last line's content as written. A
85//!   backend that writes the lines back therefore never writes a final `\\`,
86//!   which would make LaTeX add the space of an empty line after the last
87//!   equation. Anything else after the last `\\` (mathematics, a `\label`, a
88//!   `\tag` or a `\nonumber`) begins a further line.
89//!
90//! A line's `linebreak` is therefore `Some` exactly when another line follows it.
91//!
92//! # The error, and empty lines
93//!
94//! The body parser of the display-math environments ([`LinesBehavior`]) checks
95//! the lines when a body is parsed and reports one condition as an Error:
96//! [`LabelWithoutNumber`] (`flm.math.label-without-number`), a `\label` or a
97//! `\tag` written on a line that cannot be numbered, a line marked `\nonumber`
98//! or any line of `equation*`, `align*` or `gather*`. Each such command is
99//! reported once.
100//!
101//! Whether a line must hold mathematics is a question for the feature that
102//! processes mathematics, not for this module: a line holding only whitespace,
103//! comments, a `\label`, a `\tag` or a `\nonumber`, a `\\` at the start of a
104//! body, two `\\` in a row and an empty body are read here without a report.
105//! A processing feature reports each such line from its check stage, as
106//! [`math-passthrough`](crate::math_passthrough) does.
107//!
108//! The tree keeps the body as written, and [`equation_lines`] returns every
109//! line, an empty line as an [`EquationLine`] with no content, so that a backend
110//! can still write back what the author wrote.
111//!
112//! # Lowering
113//!
114//! None of the four commands is lowered on its own. Their nodes are only ever
115//! written inside an environment's body, which the environment's lowering rule
116//! reads as lines and writes from the lines' data. A field node that reaches a
117//! backend on its own is an Error, reported by the only lowering rule of the
118//! field element ([`FieldRule`](crate::stdlib::backends::lowering::FieldRule)).
119//!
120//! # The lines and the numbers
121//!
122//! The environment declares one reference point per line, whose index is the
123//! line's index. A line that can be numbered carries the labels written on it, so
124//! `\ref{eq:name}` refers to the line it labels and shows the number the document
125//! gave that line; a line that cannot be numbered keeps no label, so nothing can
126//! refer to it. A line's `\tag` replaces its number: the reference point states the tag's content ([`Tag::content_ref`]), and the
127//! line counts in nothing. The [`math`](super) feature's documentation describes
128//! the reference points in full.
129//!
130//! # Map of the module
131//!
132//! - [`PACKAGE`], [`package`] — the scoped package of the four commands.
133//! - [`LINEBREAK_COMMAND`], [`TAG_COMMAND`], [`NONUMBER_COMMAND`],
134//!   [`SPACING_ARG`], [`STAR_ARG`], [`TEXT_ARG`] — the names of the commands and
135//!   of their arguments.
136//! - [`equation_lines`], [`EquationLine`] — the reader and what it returns for one
137//!   line; [`line_break`], [`LineBreak`], [`tag_of`], [`Tag`] — the readers of
138//!   one `\\` and one `\tag`.
139//! - [`LinesBehavior`], [`body_behavior`] — the body parser of the environments.
140//! - [`LabelWithoutNumber`], [`LineCommand`] — the condition the parse reports.
141
142// The lines are read by this one reader, of the feature that owns the
143// environments, so that a backend writing an environment back line by line
144// and the numbering of the lines agree on which line a label belongs to. The
145// `\label` written here is a field like the other three: it is data of its
146// line, as a `\tag` is. The four commands are scoped to the environments'
147// bodies, as in the Python implementation: in other mathematics, `\\` and
148// `\label` would become nodes no consumer wants. Each line has its own
149// reference point, so that a reference lands on the line its label is
150// written on.
151
152use std::fmt;
153use std::sync::Arc;
154
155use techy::core::constructs::{
156    ArgumentParser, ConstructParser, ConstructParserResult, EnvironmentBody, EnvironmentBodyParser,
157    OptionalGroupArgumentParser, ParseContext, ParsedArgumentNodes,
158};
159use techy::core::node::{BodySlotExt, BuildId, NodeKind, NodeRef, NodeSlice, StagedNodes};
160use techy::core::specs::ArgumentSpec;
161use techy::core::token::GroupRule;
162use techy::core::ParsingStateDelta;
163use techy::error::{DiagnosticInfo, DiagnosticValue, ToDiagnosticValue};
164use techy::latexlike::{EnvironmentBehavior, EnvironmentInvocation, Mode};
165use techy::source::{Source, SourceSpan};
166
167use crate::lang::{Flm, FlmSpan};
168use crate::lang::flm::FlmGroupType;
169use crate::lang::origin::FlmOrigin;
170use crate::lang::structural;
171use crate::lang::mint::{
172    ArgDef, ArgStdKind, DefinitionShape, ElementDef, FlmArgumentParser, FlmBodyParser,
173    ScopedPackageDef, SyntaxDef, field_element,
174    is_field_named,
175};
176use crate::lang::text::is_blank_text;
177use crate::model::aspects::ContentRef;
178use crate::model::element::ElementSpec;
179use crate::model::names::{FeatureName, Name};
180use crate::stdlib::features::refs::{self, LabelUse};
181
182/// The name of the scoped package that holds the four commands,
183/// `flm.math.lines`: the body declaration of each display-math environment
184/// refers to it, which makes the commands available inside the body.
185pub const PACKAGE: &str = "flm.math.lines";
186
187/// The name of the line-break field, a single backslash: the author writes
188/// it after the escape character, so the command reads `\\`.
189pub const LINEBREAK_COMMAND: &str = "\\";
190
191/// The name of the tag field, `tag`.
192pub const TAG_COMMAND: &str = "tag";
193
194/// The name of the no-number field, `nonumber`.
195pub const NONUMBER_COMMAND: &str = "nonumber";
196
197/// The name of the optional argument of `\\`, `spacing`: the vertical space
198/// added after the line, as in `\\[1ex]`.
199pub const SPACING_ARG: &str = "spacing";
200
201/// The name of the star argument of `\tag`, `star`: when it is written
202/// (`\tag*`), the tag is shown without parentheses.
203pub const STAR_ARG: &str = "star";
204
205/// The name of the mandatory argument of `\tag`, `text`: the tag's content,
206/// read in text mode.
207pub const TEXT_ARG: &str = "text";
208
209/// The syntax of `\\`: one optional `[…]` argument named [`SPACING_ARG`],
210/// which must follow the command immediately and is read by [`SpacingParser`];
211/// its content is kept as written.
212fn linebreak_syntax() -> SyntaxDef {
213    SyntaxDef::Macro { args: vec![ArgDef::named(SPACING_ARG, SpacingParser::new())] }
214}
215
216/// The parser of the spacing argument of `\\` ([`SPACING_ARG`]): an optional
217/// `[…]` group that must follow the command immediately, as in `\\[1ex]`.
218///
219/// An optional argument of a standard kind ([`ArgStdKind::Optional`]) may be
220/// written after whitespace, so the argument uses this parser instead: techy's
221/// parser of an optional group, required to be adjacent, so that only a `[`
222/// written directly after the command opens the argument. A single group
223/// inside the brackets is not unwrapped, so `\\[{1ex}]` records its spacing
224/// as `{1ex}`, exactly as written.
225///
226/// Otherwise the parser behaves as the parser of an optional group: the
227/// argument is read in the mode of the body it is written in (math mode),
228/// declares no field, and is written as a value when a user definition is
229/// recomposed. Its identity is its own, distinct from the optional group's.
230#[derive(Debug)]
231struct SpacingParser(OptionalGroupArgumentParser<Flm>);
232
233impl SpacingParser {
234    /// The parser of `[…]` directly after the command.
235    fn new() -> SpacingParser {
236        let brackets = Arc::new(GroupRule {
237            group_type: FlmGroupType::Content,
238            open: String::from("["),
239            close: String::from("]"),
240        });
241        SpacingParser(OptionalGroupArgumentParser::<Flm>::new(brackets).require_adjacent())
242    }
243}
244
245impl ArgumentParser<Flm> for SpacingParser {
246    fn parse_argument(
247        &self,
248        cx: &mut ParseContext<'_, '_, Flm>,
249        spec: &ArgumentSpec<Flm>,
250    ) -> ConstructParserResult<Flm, Option<ParsedArgumentNodes<Flm>>> {
251        self.0.parse_argument(cx, spec)
252    }
253
254    fn can_match_empty(&self) -> bool {
255        self.0.can_match_empty()
256    }
257}
258
259impl FlmArgumentParser for SpacingParser {
260    fn identity(&self) -> Vec<u8> {
261        b"flm.math.lines.spacing".to_vec()
262    }
263
264    fn definition_shape(&self) -> DefinitionShape {
265        DefinitionShape::Value
266    }
267
268    fn description(&self) -> String {
269        String::from("an optional `[…]` group written directly after the command")
270    }
271}
272
273/// The declaration of `\\`.
274fn linebreak_def(owner: &FeatureName) -> ElementDef {
275    ElementDef::new(
276        owner.clone(),
277        [LINEBREAK_COMMAND],
278        linebreak_syntax(),
279        field_element(
280            "A `\\\\` inside a display-math environment: the end of an equation line, \
281             with the optional vertical spacing written after it.",
282        ),
283    )
284    .modes([Mode::Math])
285    .docs("Ends an equation line; the optional argument is vertical spacing.")
286}
287
288/// The declaration of `\tag` and `\tag*`.
289fn tag_def(owner: &FeatureName) -> ElementDef {
290    ElementDef::new(
291        owner.clone(),
292        [TAG_COMMAND],
293        SyntaxDef::Macro {
294            args: vec![
295                ArgDef::named(STAR_ARG, ArgStdKind::Star)
296                    .docs("A star: the text is shown as written, without parentheses."),
297                ArgDef::named(TEXT_ARG, ArgStdKind::Mandatory)
298                    .mode(Mode::Text)
299                    .docs("The tag's text, as ordinary document content."),
300            ],
301        },
302        field_element(
303            "A `\\tag{…}` or `\\tag*{…}` inside a display-math environment: a custom tag \
304             for the equation line, replacing its number.",
305        ),
306    )
307    .modes([Mode::Math])
308    .docs(
309        "Gives the line a custom tag in place of its number, shown in parentheses unless \
310         the command is starred. The text is read in text mode, so it is ordinary document \
311         content: a command inside it is read as a command, and a character an output \
312         format must escape is escaped.",
313    )
314}
315
316/// The declaration of `\nonumber`.
317fn nonumber_def(owner: &FeatureName) -> ElementDef {
318    ElementDef::new(
319        owner.clone(),
320        [NONUMBER_COMMAND],
321        SyntaxDef::Macro { args: Vec::new() },
322        field_element(
323            "A `\\nonumber` inside a display-math environment: the equation line is not \
324             to be numbered.",
325        ),
326    )
327    .modes([Mode::Math])
328    .docs("Marks the line as not numbered.")
329}
330
331/// The declaration of `\label{…}`: a macro whose only argument, a group of
332/// characters, has the name that the `refs` feature gives it
333/// ([`TARGET_ARG`](crate::stdlib::features::refs::TARGET_ARG)), so that that
334/// feature's reader of a label node reads it, and whose element is the field
335/// of the same name as the `\label` a heading reads.
336fn label_def(owner: &FeatureName) -> ElementDef {
337    ElementDef::new(
338        owner.clone(),
339        [refs::LABEL_FIELD],
340        SyntaxDef::Macro {
341            args: vec![
342                ArgDef::named(refs::TARGET_ARG, ArgStdKind::CharsGroup)
343                    .docs("The label, `type:label` (`eq:main`).")
344                    .role(refs::DEFINED_LABEL_ARG_ROLE),
345            ],
346        },
347        field_element(
348            "A `\\label{type:label}` inside a display-math environment: a label on the \
349             equation line it is written on.",
350        ),
351    )
352    .modes([Mode::Math])
353    .docs("Attaches a label to the equation line it is written on.")
354}
355
356/// The scoped package [`PACKAGE`] with the declarations of the four commands,
357/// owned by `owner`: what the `math` feature registers, and what the body of
358/// each display-math environment refers to.
359///
360/// The registry's feature builder attributes the package and its declarations
361/// to the feature that registers it, regardless of `owner`; the parameter
362/// matters only for a package built outside a registry.
363pub fn package(owner: impl Into<FeatureName>) -> ScopedPackageDef {
364    let owner = owner.into();
365    ScopedPackageDef {
366        owner: owner.clone(),
367        name: Name::from(PACKAGE),
368        elements: vec![
369            linebreak_def(&owner),
370            tag_def(&owner),
371            nonumber_def(&owner),
372            label_def(&owner),
373        ],
374        docs: String::from(
375            "The commands of a display-math environment's body: `\\\\`, `\\label`, `\\tag` \
376             and `\\nonumber`.",
377        ),
378    }
379}
380
381// --- the environment behavior and its error -----------------------------------------------
382
383/// The command that a [`LabelWithoutNumber`] condition reports: `\label` or
384/// `\tag`.
385#[derive(Debug, Clone, Copy, PartialEq, Eq)]
386pub enum LineCommand {
387    /// A `\label`.
388    Label,
389    /// A `\tag`.
390    Tag,
391}
392
393impl LineCommand {
394    /// The command's name without the escape character: `label` or `tag`.
395    /// The diagnostic's data holds the command under this name.
396    pub fn name(self) -> &'static str {
397        match self {
398            LineCommand::Label => "label",
399            LineCommand::Tag => "tag",
400        }
401    }
402}
403
404impl fmt::Display for LineCommand {
405    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
406        f.write_str(self.name())
407    }
408}
409
410impl ToDiagnosticValue for LineCommand {
411    fn to_diagnostic_value(&self) -> DiagnosticValue {
412        DiagnosticValue::Str(String::from(self.name()))
413    }
414}
415
416/// Condition `flm.math.label-without-number` (an Error): a `\label` or a
417/// `\tag` is written on an equation line that cannot be numbered, a line
418/// marked `\nonumber` or any line of a starred environment (`equation*`,
419/// `align*`, `gather*`).
420///
421/// [`LinesBehavior`] reports it when the body is parsed, at the command, once
422/// per such command. The recovery is to keep the body as written:
423/// [`equation_lines`] records the label or the tag on its line, and the line's
424/// reference point keeps no label (see [`MathEnvironment`](super::MathEnvironment)).
425/// See the module documentation, *The error, and empty lines*.
426#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
427#[diagnostic(
428    id = "flm.math.label-without-number",
429    message = "`\\{command}` must not be written on a line marked `\\nonumber` or in a \
430               starred environment; line {line} (counting from 0) of the `{environment}` \
431               environment is such a line"
432)]
433pub struct LabelWithoutNumber {
434    /// The environment's name as written (`align*`).
435    pub environment: String,
436    /// The index of the line among the environment's lines, counting from zero.
437    pub line: usize,
438    /// The command written on the line: `label` or `tag`.
439    pub command: LineCommand,
440}
441
442/// The body parser ([`FlmBodyParser`]) of the six display-math environments:
443/// techy's ordinary parse of an environment body, up to and including
444/// `\end{name}`, followed by the check of the equation lines, which reports
445/// [`LabelWithoutNumber`] among the parse's diagnostics. See the module
446/// documentation, *The error, and empty lines*.
447///
448/// The parser records whether the environment numbers its lines (`align` does,
449/// `align*` does not). The body's parsing mode and its scoped package come
450/// from the body declaration that carries the parser
451/// ([`BodyDef`](crate::lang::mint::BodyDef)). Build one with
452/// [`body_behavior`].
453#[derive(Debug)]
454pub struct LinesBehavior {
455    numbered: bool,
456}
457
458/// The [`LinesBehavior`] of a display-math environment, `numbered` saying
459/// whether the environment numbers its lines: the body parser that the
460/// environment's body declaration carries
461/// ([`BodyDef::parser`](crate::lang::mint::BodyDef::parser)).
462pub fn body_behavior(numbered: bool) -> LinesBehavior {
463    LinesBehavior { numbered }
464}
465
466impl FlmBodyParser for LinesBehavior {
467    fn identity(&self) -> Vec<u8> {
468        let mut out = b"flm.math.lines".to_vec();
469        out.push(u8::from(self.numbered));
470        out
471    }
472
473    fn description(&self) -> String {
474        String::from("equation lines separated by `\\\\`, checked as they are read")
475    }
476}
477
478impl EnvironmentBehavior<Flm> for LinesBehavior {
479    fn make_body_parser<'p>(
480        &'p self,
481        invocation: EnvironmentInvocation<'p, Flm>,
482    ) -> Box<dyn ConstructParser<Flm, Output = EnvironmentBody<Flm>> + 'p> {
483        Box::new(LinesBodyParser { invocation, numbered: self.numbered })
484    }
485}
486
487/// The body parser that [`LinesBehavior`] creates for one environment: the
488/// ordinary body parse, then the check of the lines over the parsed body.
489struct LinesBodyParser<'p> {
490    invocation: EnvironmentInvocation<'p, Flm>,
491    numbered: bool,
492}
493
494impl ConstructParser<Flm> for LinesBodyParser<'_> {
495    type Output = EnvironmentBody<Flm>;
496
497    fn parse(
498        &mut self,
499        cx: &mut ParseContext<'_, '_, Flm>,
500    ) -> ConstructParserResult<Flm, (EnvironmentBody<Flm>, Option<Box<ParsingStateDelta<Flm>>>)> {
501        let invocation = &self.invocation;
502        let mut inner = EnvironmentBodyParser::new(
503            invocation.trigger_span.clone(),
504            invocation.name,
505            invocation.end_command_name,
506            FlmGroupType::Content,
507        )
508        .with_invocation_name_span(invocation.name_span.clone());
509        let (body, delta) = inner.parse(cx)?;
510        // The staged nodes are read first and reported after: reading borrows the
511        // context, reporting needs it mutably.
512        let faults = match cx.staged_nodes().get(body.body) {
513            Some(list) => {
514                let staged = cx.staged_nodes();
515                line_faults(staged, list.children(), invocation.name, self.numbered)
516            }
517            None => {
518                return Err(cx.implementation_error(
519                    "the body parser of a display-math environment returned an unstaged body",
520                    invocation.trigger_span.clone(),
521                ));
522            }
523        };
524        for (condition, span) in faults {
525            cx.recover(condition, span)?;
526        }
527        Ok((body, delta))
528    }
529}
530
531/// The labels and tags the line check finds on lines that cannot be numbered,
532/// each with the span it is reported at: `children` are the body's direct
533/// children, `environment` the environment's name and `numbered` whether it
534/// numbers its lines. The body is split into lines as [`equation_lines`]
535/// splits it.
536fn line_faults(
537    staged: StagedNodes<'_, Flm>,
538    children: &[BuildId],
539    environment: &str,
540    numbered: bool,
541) -> Vec<(LabelWithoutNumber, FlmSpan)> {
542    let pieces = children.iter().filter_map(|id| {
543        let node = staged.get(*id)?;
544        let piece = piece_of(node.kind(), &node.ext().element, node.span().source());
545        Some((piece, node.span().clone()))
546    });
547    let mut faults = Vec::new();
548    for (line, segment) in split(pieces).into_iter().enumerate() {
549        let unnumbered = !numbered || segment.items.iter().any(|(piece, _)| *piece == Piece::NoNumber);
550        if unnumbered {
551            for (piece, span) in &segment.items {
552                let command = match piece {
553                    Piece::Label => LineCommand::Label,
554                    Piece::Tag => LineCommand::Tag,
555                    _ => continue,
556                };
557                let condition =
558                    LabelWithoutNumber { environment: String::from(environment), line, command };
559                faults.push((condition, span.clone()));
560            }
561        }
562    }
563    faults
564}
565
566/// The equation lines of a display-math environment that hold no mathematics,
567/// each as its index among the lines (counting from zero) and the span a
568/// report of it points at: the line's `\label`, `\tag` and `\nonumber`
569/// commands (from the first to the last), or the `\\` that ends the line when
570/// it holds none, or the environment's body when the body is entirely empty.
571///
572/// Whitespace (a blank line included), comments and the four commands of the
573/// body are not mathematics. The body is split into lines as
574/// [`equation_lines`] splits it, so the indices are those of the list it
575/// returns. A node with no body has no lines.
576///
577/// A feature that processes mathematics reports these lines, for example
578/// [`math-passthrough`](crate::math_passthrough).
579pub(crate) fn empty_lines(node: &NodeRef<'_, Flm>) -> Vec<(usize, FlmSpan)> {
580    let Some(body) = node.body() else {
581        return Vec::new();
582    };
583    let pieces = body.iter().map(|child| {
584        let piece = piece_of(child.kind(), &child.ext().element, child.span().source());
585        (piece, child.span().clone())
586    });
587    let mut empty = Vec::new();
588    for (line, segment) in split(pieces).into_iter().enumerate() {
589        if segment.items.iter().any(|(piece, _)| *piece == Piece::Content) {
590            continue;
591        }
592        let commands: Vec<&FlmSpan> = segment
593            .items
594            .iter()
595            .filter(|(piece, _)| *piece != Piece::Blank)
596            .map(|(_, span)| span)
597            .collect();
598        let span = match (cover(&commands), &segment.linebreak) {
599            (Some(span), _) => span,
600            (None, Some(brk)) => brk.clone(),
601            (None, None) => body_span(node),
602        };
603        empty.push((line, span));
604    }
605    empty
606}
607
608/// The span of a node's body: the span of the node that wraps the body's
609/// content, where the parse made one, and otherwise the span the content
610/// covers; the node's own span when neither is known.
611fn body_span(node: &NodeRef<'_, Flm>) -> FlmSpan {
612    let wrapper = node.callable().and_then(|callable| {
613        let index = callable.slots.iter().position(|slot| slot.ext.is_body())?;
614        node.slot_content_parent(index)
615    });
616    if let Some(wrapper) = wrapper {
617        return wrapper.span().clone();
618    }
619    node.body().and_then(|body| body.span()).unwrap_or_else(|| node.span().clone())
620}
621
622/// The span from the start of the first of `spans` to the end of the last, when
623/// they lie in one source; the first span alone otherwise; `None` for no span.
624fn cover(spans: &[&FlmSpan]) -> Option<FlmSpan> {
625    let first = spans.first()?;
626    let last = spans.last()?;
627    if first.same_source(last) {
628        Some(SourceSpan::new(first.source(), first.start()..last.end()))
629    } else {
630        Some((*first).clone())
631    }
632}
633
634// --- reading -------------------------------------------------------------------------------
635
636/// The text a run of nodes was written as: the source they cover, taken as
637/// one slice when the nodes cover one source without gaps, and otherwise each
638/// node's own source text, joined.
639fn written(nodes: &NodeSlice<'_, Flm>) -> String {
640    match nodes.source_text() {
641        Some(text) => text.to_string(),
642        None => nodes.iter().map(|node| node.span_content()).collect(),
643    }
644}
645
646/// A `\\` node, as [`line_break`] reads it: the node and its spacing.
647#[derive(Debug, Clone)]
648pub struct LineBreak<'t> {
649    /// The `\\` node.
650    pub node: NodeRef<'t, Flm>,
651    /// The optional argument's content exactly as written, `1ex` for
652    /// `\\[1ex]`; `None` when no argument was written.
653    pub spacing: Option<String>,
654}
655
656/// A `\tag` node, as [`tag_of`] reads it: the node, its content and whether
657/// the star was written.
658#[derive(Debug, Clone)]
659pub struct Tag<'t> {
660    /// The `\tag` node.
661    pub node: NodeRef<'t, Flm>,
662    /// The nodes of the argument's content, in order: the tag's text as
663    /// document content, lowered like any other inline content, so that a
664    /// command inside it is lowered by its own rule and a character that the
665    /// output format must escape is escaped.
666    pub content: Vec<NodeRef<'t, Flm>>,
667    /// Whether the star was given (`\tag*{…}`).
668    pub star: bool,
669}
670
671impl Tag<'_> {
672    /// Whether the tag is shown in parentheses: `\tag{A}` shows `(A)`, and
673    /// `\tag*{A}` shows `A` alone.
674    ///
675    /// This is how FLM reads the two forms: the unstarred tag adds the
676    /// parentheses a number has, and the starred one shows the content alone.
677    /// The rules of the [`math`](super) feature write `\tag*{…}` around the
678    /// content and add the parentheses themselves where this returns `true`,
679    /// so that LaTeX adds nothing further.
680    pub fn parenthesized(&self) -> bool {
681        !self.star
682    }
683
684    /// The tag's content exactly as it was written, for a consumer that wants
685    /// the source text rather than the nodes.
686    pub fn written(&self) -> String {
687        self.content.iter().map(|node| node.span_content()).collect()
688    }
689
690    /// The node that the tag's text argument was written as (the brace group
691    /// of `\tag{a note}`, the single token of `\tag 1`), as a content
692    /// reference ([`ContentRef`]): the way an aspect refers to content inside
693    /// the node it declares something about.
694    ///
695    /// The environment's reference points state it as the content of a tagged
696    /// line, so that a `\ref` to that line shows what the tag shows. It refers
697    /// to the argument as written, delimiters included, rather than to the
698    /// [`content`](Tag::content) nodes inside it, because a content reference
699    /// refers to one node, and a brace group shows exactly what it holds on
700    /// every backend.
701    ///
702    /// `None` when the argument is absent (after a parse recovery), or when it
703    /// was written as more than one node.
704    pub fn content_ref(&self) -> Option<ContentRef> {
705        let region = self.node.argument_nodes_named(TEXT_ARG).ok()??;
706        let mut nodes = region.iter();
707        let first = nodes.next()?;
708        nodes.next().is_none().then(|| ContentRef::Node(first.id()))
709    }
710}
711
712/// One equation line of a display-math environment, as [`equation_lines`]
713/// reads it: its content, labels, tag, no-number mark and line break. The
714/// module documentation, *Reading a body as lines*, says how a body is split
715/// into lines.
716#[derive(Debug, Clone, Default)]
717pub struct EquationLine<'t> {
718    /// The line's content, in order: every direct child of the body in this
719    /// line that is not a `\\`, a `\label`, a `\tag` or a `\nonumber`
720    /// (mathematics, whitespace, comments, and nested environments as a
721    /// whole). On the last line this includes, as written, the whitespace and
722    /// comments after a final `\\` that is not recorded (see the module
723    /// documentation, *Reading a body as lines*).
724    pub content: Vec<NodeRef<'t, Flm>>,
725    /// The labels written on the line, in order, each as written and, when its
726    /// text has the form `type:label`, parsed. The environment declares them
727    /// on the line's reference point, and its recomposition rule for the
728    /// `latex-recomposed` backend writes them at the line's end.
729    pub labels: Vec<LabelUse>,
730    /// The tag, when one was written; when a line has several, the last
731    /// one.
732    pub tag: Option<Tag<'t>>,
733    /// Whether `\nonumber` was written on the line.
734    pub nonumber: bool,
735    /// The `\\` that ends the line: `Some` exactly when another line follows
736    /// this one. `None` for the last line, whether or not a `\\` was written
737    /// after it: a final `\\` followed only by whitespace and comments is not
738    /// recorded, and that whitespace and those comments are part of the
739    /// line's [`content`](EquationLine::content) (see the module
740    /// documentation, *Reading a body as lines*).
741    pub linebreak: Option<LineBreak<'t>>,
742}
743
744/// Reads a `\\` node: `Some` with its spacing when `node` is the line-break
745/// field of this module, `None` for any other node.
746pub fn line_break<'t>(node: &NodeRef<'t, Flm>) -> Option<LineBreak<'t>> {
747    if !is_field_named(node, LINEBREAK_COMMAND) {
748        return None;
749    }
750    let provided = node
751        .arguments()
752        .and_then(|args| args.get_named(SPACING_ARG))
753        .is_some_and(|arg| arg.is_provided());
754    let spacing = provided.then(|| {
755        node.argument_content_nodes_named(SPACING_ARG)
756            .ok()
757            .flatten()
758            .map(|content| written(&content))
759            .unwrap_or_default()
760    });
761    Some(LineBreak { node: *node, spacing })
762}
763
764/// Reads a `\tag` node: `Some` with its content and its star when `node` is
765/// the tag field of this module, `None` for any other node. A tag whose text
766/// argument is absent (after a parse recovery) has no content.
767pub fn tag_of<'t>(node: &NodeRef<'t, Flm>) -> Option<Tag<'t>> {
768    if !is_field_named(node, TAG_COMMAND) {
769        return None;
770    }
771    let star = node
772        .arguments()
773        .and_then(|args| args.get_named(STAR_ARG))
774        .is_some_and(|arg| arg.is_provided());
775    let content = node
776        .argument_content_nodes_named(TEXT_ARG)
777        .ok()
778        .flatten()
779        .map(|content| content.iter().collect())
780        .unwrap_or_default();
781    Some(Tag { node: *node, content, star })
782}
783
784/// The class of a direct child of a body for the split into lines.
785#[derive(Debug, Clone, Copy, PartialEq, Eq)]
786enum Piece {
787    /// A `\\`: the end of a line.
788    Break,
789    /// A `\label`.
790    Label,
791    /// A `\tag`.
792    Tag,
793    /// A `\nonumber`.
794    NoNumber,
795    /// A comment, a paragraph break, or a run of characters holding only
796    /// whitespace: content of the line, but not mathematics.
797    Blank,
798    /// Anything else: mathematics, a group, a nested environment.
799    Content,
800}
801
802/// Classifies one child of a body for the split, from its node kind, its
803/// element and the source its text is read from.
804///
805/// The four commands are fields, and this is where the environment, the
806/// construct that holds them, gives each of them its meaning. A field of any
807/// other name is ordinary content of the line.
808fn piece_of(kind: &NodeKind<Flm>, element: &ElementSpec, source: &Source<FlmOrigin>) -> Piece {
809    let field = match kind {
810        NodeKind::Callable(data) if element.name == structural::FIELD => Some(&*data.name),
811        _ => None,
812    };
813    if let Some(name) = field {
814        if name == LINEBREAK_COMMAND {
815            return Piece::Break;
816        } else if name == refs::LABEL_FIELD {
817            return Piece::Label;
818        } else if name == TAG_COMMAND {
819            return Piece::Tag;
820        } else if name == NONUMBER_COMMAND {
821            return Piece::NoNumber;
822        }
823    }
824    if element.name.as_str() == structural::PARBREAK {
825        // A blank line inside the body is kept as a paragraph-break node; to the
826        // lines it is whitespace.
827        Piece::Blank
828    } else {
829        match kind {
830            NodeKind::Comment(_) => Piece::Blank,
831            NodeKind::Chars { content } if is_blank_text(content.resolve(source)) => Piece::Blank,
832            _ => Piece::Content,
833        }
834    }
835}
836
837/// One line as the split produces it: its children other than the `\\`, each
838/// with its class, and the `\\` that ends it (`None` for the last line).
839struct Segment<T> {
840    items: Vec<(Piece, T)>,
841    linebreak: Option<T>,
842}
843
844impl<T> Default for Segment<T> {
845    fn default() -> Segment<T> {
846        Segment { items: Vec::new(), linebreak: None }
847    }
848}
849
850/// Splits a body into lines; [`equation_lines`], [`empty_lines`] and the
851/// parse-time check use it. A `\\` ends a line. A `\\` followed only by blank children ends the
852/// body: it is removed from the line it ended, and the blank children after it
853/// are appended to that line in order. Anything else after the last `\\`
854/// begins a further line, which also holds the blank children between the
855/// `\\` and it. See the module documentation, *Reading a body as lines*.
856fn split<T>(pieces: impl IntoIterator<Item = (Piece, T)>) -> Vec<Segment<T>> {
857    let mut lines = Vec::new();
858    let mut line = Segment::default();
859    // Whether only blank pieces have followed the last `\\`: then the body ends
860    // with that line break.
861    let mut ends_with_break = false;
862    for (piece, value) in pieces {
863        match piece {
864            Piece::Break => {
865                line.linebreak = Some(value);
866                lines.push(std::mem::take(&mut line));
867                ends_with_break = true;
868            }
869            Piece::Blank => line.items.push((piece, value)),
870            _ => {
871                ends_with_break = false;
872                line.items.push((piece, value));
873            }
874        }
875    }
876    if ends_with_break {
877        // Only blank pieces followed the last `\\`: drop it, and give those
878        // pieces to the line it ended, in order.
879        if let Some(last) = lines.last_mut() {
880            last.linebreak = None;
881            last.items.append(&mut line.items);
882        }
883    } else {
884        lines.push(line);
885    }
886    lines
887}
888
889/// The equation lines of a display-math environment's body: one
890/// [`EquationLine`] per line, in order. The module documentation, *Reading a
891/// body as lines*, says exactly how the body is split.
892///
893/// `node` is normally a node of the element [`ENVIRONMENT`](super::ENVIRONMENT);
894/// any node with a body is read the same way. A node with no body returns no
895/// lines. An environment with an empty body has a body and returns one empty
896/// line. A final `\\` followed
897/// only by whitespace and comments is not recorded, and that whitespace and
898/// those comments are part of the last line's
899/// [`content`](EquationLine::content), as written.
900pub fn equation_lines<'t>(node: &NodeRef<'t, Flm>) -> Vec<EquationLine<'t>> {
901    let Some(body) = node.body() else {
902        return Vec::new();
903    };
904    let pieces = body.iter().map(|child| {
905        let piece = piece_of(child.kind(), &child.ext().element, child.span().source());
906        (piece, child)
907    });
908    split(pieces)
909        .into_iter()
910        .map(|segment| {
911            let mut line = EquationLine::default();
912            for (piece, child) in segment.items {
913                match piece {
914                    Piece::Label => {
915                        if let Some(label) = refs::label_use(&child) {
916                            line.labels.push(label);
917                        }
918                    }
919                    Piece::Tag => line.tag = tag_of(&child),
920                    Piece::NoNumber => line.nonumber = true,
921                    Piece::Blank | Piece::Content => line.content.push(child),
922                    Piece::Break => {}
923                }
924            }
925            line.linebreak = segment.linebreak.as_ref().and_then(line_break);
926            line
927        })
928        .collect()
929}
930
931#[cfg(test)]
932mod tests {
933    use super::*;
934    use crate::lang::structural::FIELD;
935
936    #[test]
937    fn the_package_declares_the_four_commands_in_math_mode_only() {
938        let package = package("math");
939        assert_eq!(package.name, PACKAGE);
940        let names: Vec<Vec<String>> = package
941            .elements
942            .iter()
943            .map(|def| def.names.iter().map(|n| n.to_string()).collect())
944            .collect();
945        assert_eq!(names, [vec!["\\"], vec!["tag"], vec!["nonumber"], vec!["label"]]);
946        assert!(package.elements.iter().all(|def| def.modes == vec![Mode::Math]));
947        assert!(package.elements.iter().all(|def| def.owner == "math"));
948    }
949
950    #[test]
951    fn every_declaration_is_a_field_named_for_the_command() {
952        let package = package("math");
953        let fields: Vec<&str> = package
954            .elements
955            .iter()
956            .map(|def| {
957                assert_eq!(def.element.name, FIELD, "every line command is a field");
958                def.names[0].as_str()
959            })
960            .collect();
961        assert_eq!(fields, [LINEBREAK_COMMAND, TAG_COMMAND, NONUMBER_COMMAND, refs::LABEL_FIELD]);
962    }
963
964    #[test]
965    fn the_split_drops_a_final_break_and_opens_a_line_for_a_command_after_it() {
966        use Piece::*;
967        let pieces = |seq: &[Piece]| seq.iter().enumerate().map(|(i, p)| (*p, i)).collect::<Vec<_>>();
968        // `a \\ %% c` : one line, its break dropped, the blank after it on that line.
969        let lines = split(pieces(&[Content, Break, Blank]));
970        assert_eq!(lines.len(), 1);
971        assert_eq!(lines[0].items.iter().map(|(p, v)| (*p, *v)).collect::<Vec<_>>(), [(Content, 0), (Blank, 2)]);
972        assert!(lines[0].linebreak.is_none());
973        // `a \\ \label{x}` : two lines, the first keeps its break.
974        let lines = split(pieces(&[Content, Break, Blank, Label]));
975        assert_eq!(lines.len(), 2);
976        assert_eq!(lines[0].linebreak, Some(1));
977        assert_eq!(lines[1].items.iter().map(|(p, _)| *p).collect::<Vec<_>>(), [Blank, Label]);
978        assert!(lines[1].linebreak.is_none());
979        // `\\ \\ %% c` : two empty lines; the second break is the final one,
980        // and the blank after it is on the second line.
981        let lines = split(pieces(&[Break, Blank, Break, Blank]));
982        assert_eq!(lines.len(), 2);
983        assert_eq!(lines[0].linebreak, Some(0));
984        assert_eq!(lines[1].items.iter().map(|(p, v)| (*p, *v)).collect::<Vec<_>>(), [(Blank, 1), (Blank, 3)]);
985        assert!(lines[1].linebreak.is_none());
986        // nothing at all: one empty line.
987        assert_eq!(split(pieces(&[])).len(), 1);
988    }
989
990}