Skip to main content

flm_core/stdlib/features/cells/
reader.rs

1//! The reader of a table of cells: [`read_grid`] reads the body of a `cells`
2//! environment into the table's grid, at lowering.
3//!
4//! Every rule that lowers a table calls [`read_grid`], and nothing stores
5//! its result. It reads the table in two passes. The first pass collects the
6//! names of the rows and columns, then reads the instructions in order,
7//! keeping a current row and column, and places every cell whose rectangle
8//! is closed, which fixes the table's size. The second pass gives each cell
9//! spanning "to the end" (`\merge{2-}`) the end of the table as finally
10//! built. Then the cells are checked for overlaps, and the later of two
11//! overlapping cells is left out.
12//!
13//! # The result
14//!
15//! A [`Grid`]: the table's model, which is the payload of the
16//! `flm.pres.cells` node the rule stages ([`CellsPayload`]); the content of
17//! each cell, in the order of the model's entries ([`CellContent`]); every
18//! problem found, each with the dropped mark for what it left out, where it
19//! left something out ([`Problem`]); and the cell styles the table's tokens
20//! refer to.
21
22// The placement algorithm follows the Python implementation of FLM step for
23// step: the current row and column, the order in which the cells are
24// placed, and the four parsers of an index, a range, a placement and a
25// mapping.
26
27use std::collections::BTreeMap;
28
29use techy::core::node::{NodeRef, NodeSlice};
30use techy::error::{Diagnostic, DiagnosticInfo};
31
32use crate::core::lowering::{LowerError, chars_at_lowering};
33use crate::lang::structural;
34use crate::lang::text::{is_blank_text, is_space};
35use crate::lang::{Flm, FlmDiagnostic, FlmGroupType};
36use crate::model::element::element_of;
37use crate::model::names::Name;
38use crate::stdlib::backends::lowering::is_blank;
39use crate::stdlib::backends::pres::{
40    CellSpec, CellsPayload, DroppedPayload, MAX_CELLS_POSITIONS,
41};
42
43use super::diagnostics::{
44    BadNames, BadPlacement, BadStyleValue, BadStyles, ContentOutsideCell, Empty, Overlap, TooLarge,
45    UnknownStyle,
46};
47use super::styles::{Effect, StyleForm, Styles};
48use super::{
49    CELL, COLNAMES, COLUMN, CONTENT_ARG, DATA, DATA_ARG, MAPPING_ARG, MERGE, NAMES_ARG, PLACEMENT_ARG,
50    RANGE_ARG, ROW, ROWNAMES, STYLES_ARG,
51};
52
53/// The content of one cell of a [`Grid`]: the nodes of the document that
54/// hold it.
55#[derive(Debug, Clone, Copy)]
56pub enum CellContent<'t> {
57    /// The content argument of a `\cell`, laid out as blocks.
58    Blocks(NodeSlice<'t, Flm>),
59    /// One entry of a `\celldata`'s data: inline content, which the rule sets
60    /// as one paragraph so that a cell holds blocks on every backend.
61    Inline(NodeSlice<'t, Flm>),
62}
63
64/// One problem the reader found in a table: the Error to report and, where
65/// the reader left something out, the dropped mark to place for it.
66#[derive(Debug, Clone)]
67pub struct Problem {
68    /// The Error, at the node it concerns.
69    pub diagnostic: FlmDiagnostic,
70    /// The payload of the dropped mark (`flm.pres.dropped`) for what was
71    /// left out, where something was; the rule stages the marks before the
72    /// table, in the order of the problems.
73    pub dropped: Option<DroppedPayload>,
74}
75
76/// A table of cells as its reader reads it ([`read_grid`]).
77#[derive(Debug, Clone)]
78pub struct Grid<'t> {
79    /// The table's model: its size and one entry per cell, in row-major order
80    /// of the cells' top-left positions — the payload of the `flm.pres.cells`
81    /// node the rule stages.
82    pub payload: CellsPayload,
83    /// The content of each cell, in the order of the model's entries.
84    pub contents: Vec<CellContent<'t>>,
85    /// Every problem found, in the order of the body.
86    pub problems: Vec<Problem>,
87    /// Every cell style that a token of the table refers to, once each, in
88    /// the order of first use. On the backend it runs on, the rule requires
89    /// (records a requirement for) what each of these cell styles declares
90    /// for that backend ([`CellStyle::requires`](super::CellStyle::requires)):
91    /// style definitions on HTML, definition pieces or package requests on
92    /// the recomposed LaTeX.
93    pub styles: Vec<Name>,
94}
95
96/// Reads the table of cells `node` — a `cells` environment — against the
97/// style declarations `styles`.
98///
99/// The names of the rows and the columns are read first, then every
100/// instruction of the body, in order. This function reports nothing: each
101/// problem it finds is returned in [`Grid::problems`] with the Error to
102/// report and, where something was left out, the dropped mark to place, and
103/// the rule that calls it reports them; [diagnostics](super::diagnostics)
104/// states the recovery for each. The table itself is never refused. A node
105/// with no body gives a grid with no cells, whose only problem is
106/// [`Empty`]. Characters are read through [`chars_at_lowering`], the only
107/// way a rule reads characters at lowering.
108///
109/// # Errors
110///
111/// [`LowerError::PlaceholderCharacters`] where a placement, a mapping, a
112/// styles argument, a `\merge` range or a list of names holds a placeholder
113/// of a user definition's template that is lowered without being expanded:
114/// its characters are not known until the template is expanded.
115pub fn read_grid<'t>(node: &NodeRef<'t, Flm>, styles: &Styles) -> Result<Grid<'t>, LowerError> {
116    let body: Vec<NodeRef<'t, Flm>> = node.body().map(|body| body.iter().collect()).unwrap_or_default();
117    let mut reader = Reader::new(styles);
118    // The first pass: the names, then every instruction in order.
119    for child in &body {
120        let name = element_of(child).name.as_str();
121        if name == ROWNAMES || name == COLNAMES {
122            reader.names(child, if name == ROWNAMES { Axis::Row } else { Axis::Col })?;
123        }
124    }
125    for child in &body {
126        reader.instruction(child)?;
127    }
128    // The second pass, and the grid.
129    Ok(reader.finish(node))
130}
131
132// --- the reader's state ---------------------------------------------------------------------
133
134/// A row or a column.
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136enum Axis {
137    Row,
138    Col,
139}
140
141impl Axis {
142    fn word(self) -> &'static str {
143        match self {
144            Axis::Row => "row",
145            Axis::Col => "column",
146        }
147    }
148
149    fn index(self) -> usize {
150        match self {
151            Axis::Row => 0,
152            Axis::Col => 1,
153        }
154    }
155}
156
157/// A range of indices along one axis, from zero: `start` included, `end`
158/// excluded; an `end` of `None` spans to the end of the table.
159type Span = (u64, Option<u64>);
160
161/// Where a cell goes: its rows and its columns.
162#[derive(Debug, Clone, Copy)]
163struct Rect {
164    row: Span,
165    col: Span,
166}
167
168/// A placement or a mapping that cannot be read: what is wrong with it.
169struct Bad(String);
170
171/// What an index that is left out or written `.` means.
172#[derive(Clone, Copy)]
173enum IndexDefault {
174    /// The current row or column.
175    Current,
176    /// The value given: `None` for "left open".
177    Value(Option<u64>),
178}
179
180/// One piece of a placement or a mapping: characters, or a `\merge`.
181#[derive(Clone)]
182enum Piece<'t> {
183    Text(String),
184    Merge(NodeRef<'t, Flm>),
185}
186
187impl Piece<'_> {
188    fn is_blank(&self) -> bool {
189        matches!(self, Piece::Text(text) if is_blank_text(text))
190    }
191}
192
193/// One style token: its name, its value, and the node it was read from.
194struct Token<'t> {
195    name: String,
196    value: Option<String>,
197    at: NodeRef<'t, Flm>,
198}
199
200/// A style token resolved against its declaration.
201type Resolved = (Effect, Name);
202
203/// A cell placed by the first pass.
204struct Placed<'t> {
205    rect: Rect,
206    styles: Vec<Resolved>,
207    content: CellContent<'t>,
208    at: NodeRef<'t, Flm>,
209}
210
211/// A problem, with the place in the body it belongs to.
212struct Found {
213    order: u64,
214    problem: Problem,
215}
216
217/// The mapping of a `\celldata`: the rows and the columns its data goes to.
218#[derive(Default)]
219struct Mapping {
220    rows: Vec<Span>,
221    cols: Vec<Span>,
222}
223
224impl Mapping {
225    /// The range of the `j`-th entry along one axis: the mapping's own, the
226    /// open range continued one per entry past its start, the last range
227    /// repeated past the end, or the current index where the mapping gives
228    /// none.
229    fn get(spans: &[Span], j: u64, current: u64) -> Span {
230        let Some(&last) = spans.last() else { return (current, Some(current + 1)) };
231        let len = spans.len() as u64;
232        if j < len - 1 {
233            return spans[j as usize];
234        }
235        match last {
236            (start, None) => {
237                let index = start + (j + 1 - len);
238                (index, Some(index + 1))
239            }
240            closed => closed,
241        }
242    }
243}
244
245struct Reader<'s, 't> {
246    styles: &'s Styles,
247    current_row: u64,
248    current_col: u64,
249    /// The size so far: rows, columns.
250    size: [u64; 2],
251    /// The names of the rows and of the columns.
252    names: [BTreeMap<String, u64>; 2],
253    cells: Vec<(u64, Placed<'t>)>,
254    problems: Vec<Found>,
255    /// The cell styles referred to, once each.
256    used: Vec<Name>,
257    /// The place in the body of the instruction being read, counted.
258    order: u64,
259}
260
261impl<'s, 't> Reader<'s, 't> {
262    fn new(styles: &'s Styles) -> Reader<'s, 't> {
263        Reader {
264            styles,
265            current_row: 0,
266            current_col: 0,
267            size: [0, 0],
268            names: [BTreeMap::new(), BTreeMap::new()],
269            cells: Vec::new(),
270            problems: Vec::new(),
271            used: Vec::new(),
272            order: 0,
273        }
274    }
275
276    fn report(&mut self, at: &NodeRef<'t, Flm>, info: impl DiagnosticInfo + 'static, dropped: Option<DroppedPayload>) {
277        let diagnostic = Diagnostic::error(info, at.span().clone());
278        self.problems.push(Found { order: self.order, problem: Problem { diagnostic, dropped } });
279    }
280
281    fn current(&self, axis: Axis) -> u64 {
282        match axis {
283            Axis::Row => self.current_row,
284            Axis::Col => self.current_col,
285        }
286    }
287
288    fn move_next_row(&mut self) {
289        self.current_row += 1;
290        self.current_col = 0;
291    }
292
293    // --- the names --------------------------------------------------------------------------
294
295    fn names(&mut self, node: &NodeRef<'t, Flm>, axis: Axis) -> Result<(), LowerError> {
296        let Ok(Some(content)) = node.argument_content_nodes_named(NAMES_ARG) else { return Ok(()) };
297        let text = match chars_at_lowering(content.iter())? {
298            Ok(text) => text,
299            Err(_) => {
300                let detail = format!("The {} names may hold only names separated by commas", axis.word());
301                self.report(node, BadNames { detail }, None);
302                return Ok(());
303            }
304        };
305        let word = axis.word();
306        for (k, entry) in text.split(',').enumerate() {
307            let entry = entry.trim_matches(is_space);
308            let index = k as u64;
309            if entry.is_empty() {
310                continue;
311            }
312            let detail = if !is_name(entry) {
313                format!(
314                    "Invalid {word} name ‘{entry}’: names must begin with an ASCII letter and \
315                     contain only ASCII letters, digits and underscores"
316                )
317            } else if self.names[axis.index()].contains_key(entry) {
318                format!("The {word} name ‘{entry}’ may be declared once only")
319            } else if self.names[axis.index()].values().any(|&named| named == index) {
320                format!("Invalid name ‘{entry}’ for {word} {}: a {word} may have one name only", index + 1)
321            } else {
322                self.names[axis.index()].insert(entry.to_string(), index);
323                continue;
324            };
325            self.report(node, BadNames { detail }, None);
326        }
327        Ok(())
328    }
329
330    // --- the body's instructions -------------------------------------------------------------
331
332    fn instruction(&mut self, node: &NodeRef<'t, Flm>) -> Result<(), LowerError> {
333        if is_comment_or_blank(node) {
334            return Ok(());
335        }
336        self.order += 1;
337        let element = element_of(node).name.as_str();
338        match element {
339            CELL => {
340                self.cell(node, None, &[])?;
341            }
342            DATA => self.celldata(node)?,
343            ROW => self.move_next_row(),
344            ROWNAMES | COLNAMES => {}
345            structural::PARBREAK => {}
346            _ => {
347                let dropped = DroppedPayload {
348                    condition: Name::from("flm.cells.content-outside-cell"),
349                    detail: String::from("content outside \\cell"),
350                };
351                self.report(node, ContentOutsideCell, Some(dropped));
352            }
353        }
354        Ok(())
355    }
356
357    /// A `\cell`, placed where its own placement says, else at `default` (the
358    /// `\celldata` entry it stands for), else at the current row and column;
359    /// its own style tokens come before `default_styles`. Returns the number
360    /// of columns it spans, by which a `\celldata` advances.
361    fn cell(
362        &mut self,
363        node: &NodeRef<'t, Flm>,
364        default: Option<Rect>,
365        default_styles: &[Resolved],
366    ) -> Result<u64, LowerError> {
367        let mut styles = match node.argument_content_nodes_named(STYLES_ARG) {
368            Ok(Some(content)) => {
369                let lists = self.style_lists(node, content, false)?;
370                self.resolve(lists.into_iter().next().unwrap_or_default())
371            }
372            _ => Vec::new(),
373        };
374        styles.extend_from_slice(default_styles);
375        let fallback = default.unwrap_or(Rect {
376            row: (self.current_row, Some(self.current_row + 1)),
377            col: (self.current_col, Some(self.current_col + 1)),
378        });
379        let rect = match node.argument_content_nodes_named(PLACEMENT_ARG) {
380            Ok(Some(content)) => match self.placement(content)? {
381                Ok(rect) => rect,
382                Err(Bad(detail)) => {
383                    self.report(node, BadPlacement { detail }, None);
384                    fallback
385                }
386            },
387            _ => fallback,
388        };
389        let content = match node.argument_content_nodes_named(CONTENT_ARG) {
390            Ok(Some(content)) => content,
391            _ => empty_slice(node),
392        };
393        Ok(self.add(rect, styles, CellContent::Blocks(content), node))
394    }
395
396    /// Places one cell, and advances the current column past it. Returns the
397    /// number of columns it spans.
398    fn add(&mut self, rect: Rect, styles: Vec<Resolved>, content: CellContent<'t>, at: &NodeRef<'t, Flm>) -> u64 {
399        let [rows, cols] = self.size;
400        // A span to the end of the table covers its first index at least now,
401        // and is given its end by the second pass.
402        let row_end = rect.row.1.unwrap_or(rect.row.0 + 1).max(rect.row.0 + 1);
403        let col_end = rect.col.1.unwrap_or((rect.col.0 + 1).max(cols));
404        let new_rows = rows.max(row_end);
405        let new_cols = cols.max(col_end.max(rect.col.0 + 1));
406        let span = col_end.saturating_sub(rect.col.0);
407        self.current_col = col_end;
408        if new_rows.saturating_mul(new_cols) > MAX_CELLS_POSITIONS {
409            let dropped = DroppedPayload {
410                condition: Name::from("flm.cells.too-large"),
411                detail: String::from("cell making the table too large"),
412            };
413            self.report(at, TooLarge { limit: MAX_CELLS_POSITIONS, rows: new_rows, cols: new_cols }, Some(dropped));
414            return span;
415        }
416        self.size = [new_rows, new_cols];
417        self.cells.push((self.order, Placed { rect, styles, content, at: *at }));
418        span
419    }
420
421    fn celldata(&mut self, node: &NodeRef<'t, Flm>) -> Result<(), LowerError> {
422        let lists = match node.argument_content_nodes_named(STYLES_ARG) {
423            Ok(Some(content)) => self.style_lists(node, content, true)?,
424            _ => vec![Vec::new()],
425        };
426        let lists: Vec<Vec<Resolved>> = lists.into_iter().map(|list| self.resolve(list)).collect();
427        let mapping = match node.argument_content_nodes_named(MAPPING_ARG) {
428            Ok(Some(content)) => match self.mapping(content)? {
429                Ok(mapping) => mapping,
430                Err(Bad(detail)) => {
431                    self.report(node, BadPlacement { detail }, None);
432                    Mapping::default()
433                }
434            },
435            _ => Mapping::default(),
436        };
437        let data = match node.argument_content_nodes_named(DATA_ARG) {
438            Ok(Some(content)) => content,
439            _ => empty_slice(node),
440        };
441        self.current_row = Mapping::get(&mapping.rows, 0, self.current_row).0;
442        self.current_col = Mapping::get(&mapping.cols, 0, self.current_col).0;
443        let mut rows = split(data, ROW);
444        // A trailing `\\` ends the last row and adds none, as LaTeX reads it: an
445        // empty last part after a final `\\` is dropped, while a `\\` on its own
446        // inside the data still makes an empty row.
447        if rows.len() > 1 && rows.last().is_some_and(|row| row.iter().all(|node| is_comment_or_blank(&node))) {
448            rows.pop();
449        }
450        for (row_j, row) in rows.into_iter().enumerate() {
451            let mut col_j: u64 = 0;
452            for entry in split(row, COLUMN) {
453                self.order += 1;
454                let rect = Rect {
455                    row: Mapping::get(&mapping.rows, row_j as u64, self.current_row),
456                    col: Mapping::get(&mapping.cols, col_j, self.current_col),
457                };
458                let styles = lists[(col_j as usize).min(lists.len() - 1)].clone();
459                let shown: Vec<NodeRef<'t, Flm>> = entry
460                    .iter()
461                    .filter(|node| !is_comment_or_blank(node))
462                    .collect();
463                match shown.as_slice() {
464                    [one] if element_of(one).name.as_str() == CELL => {
465                        col_j += self.cell(one, Some(rect), &styles)?;
466                    }
467                    [] => {
468                        self.current_col = rect.col.1.unwrap_or(rect.col.0 + 1);
469                        col_j += 1;
470                    }
471                    [first, ..] => {
472                        self.add(rect, styles, CellContent::Inline(entry), first);
473                        col_j += 1;
474                    }
475                }
476            }
477            self.move_next_row();
478        }
479        Ok(())
480    }
481
482    // --- the styles ---------------------------------------------------------------------------
483
484    /// The token lists of a styles argument: one, or, where `per_entry`, one
485    /// per comma-separated list. An argument holding something other than
486    /// characters and groups is reported, and reads as one empty list.
487    fn style_lists(
488        &mut self,
489        node: &NodeRef<'t, Flm>,
490        content: NodeSlice<'t, Flm>,
491        per_entry: bool,
492    ) -> Result<Vec<Vec<Token<'t>>>, LowerError> {
493        let mut lists: Vec<Vec<Token<'t>>> = vec![Vec::new()];
494        let mut pending_values: Vec<(NodeRef<'t, Flm>, String)> = Vec::new();
495        for child in content.iter() {
496            if child.is_comment() {
497                continue;
498            }
499            if child.is_group() && child.group_type() == Some(FlmGroupType::Content) {
500                let value = match chars_at_lowering(child.children().iter())? {
501                    Ok(value) => value,
502                    Err(_) => {
503                        self.report(node, BadStyles, None);
504                        return Ok(vec![Vec::new()]);
505                    }
506                };
507                let list = lists.last_mut().expect("at least one list");
508                match list.last_mut() {
509                    Some(token) if token.value.is_none() => token.value = Some(value),
510                    _ => pending_values.push((child, value)),
511                }
512                continue;
513            }
514            let text = match chars_at_lowering(std::iter::once(child))? {
515                Ok(text) => text,
516                Err(_) => {
517                    self.report(node, BadStyles, None);
518                    return Ok(vec![Vec::new()]);
519                }
520            };
521            let pieces: Vec<&str> = if per_entry { text.split(',').collect() } else { vec![text.as_str()] };
522            for (k, piece) in pieces.into_iter().enumerate() {
523                if k > 0 {
524                    lists.push(Vec::new());
525                }
526                let list = lists.last_mut().expect("at least one list");
527                list.extend(
528                    piece
529                        .split(is_space)
530                        .filter(|name| !name.is_empty())
531                        .map(|name| Token { name: name.to_string(), value: None, at: child }),
532                );
533            }
534        }
535        for (at, value) in pending_values {
536            let detail = format!(
537                "The value ‘{{{value}}}’ must directly follow a style name, and each style name \
538                 may have only one value"
539            );
540            self.report(&at, BadStyleValue { detail }, None);
541        }
542        Ok(lists)
543    }
544
545    /// The tokens of one list, each resolved against its declaration; a token
546    /// no declaration covers, or whose value its declaration does not take,
547    /// is reported and left out.
548    fn resolve(&mut self, tokens: Vec<Token<'t>>) -> Vec<Resolved> {
549        let mut resolved = Vec::new();
550        for token in tokens {
551            let Some(style) = self.styles.get(&token.name) else {
552                self.report(&token.at, UnknownStyle { name: token.name }, None);
553                continue;
554            };
555            let effect = match (style.form, token.value) {
556                (StyleForm::Fixed(effect), None) => effect,
557                (StyleForm::Fixed(_), Some(value)) => {
558                    let detail =
559                        format!("The cell style ‘{}’ takes no value, not ‘{{{value}}}’", token.name);
560                    self.report(&token.at, BadStyleValue { detail }, None);
561                    continue;
562                }
563                (StyleForm::Structural(parameter), None) => {
564                    let detail = format!(
565                        "The cell style ‘{}’ must be given a value in braces, one of {}",
566                        token.name,
567                        quoted(parameter.values())
568                    );
569                    self.report(&token.at, BadStyleValue { detail }, None);
570                    continue;
571                }
572                (StyleForm::Structural(parameter), Some(value)) => match parameter.effect(value.trim_matches(is_space)) {
573                    Some(effect) => effect,
574                    None => {
575                        let detail = format!(
576                            "The cell style ‘{}’ takes one of {}, not ‘{value}’",
577                            token.name,
578                            quoted(parameter.values())
579                        );
580                        self.report(&token.at, BadStyleValue { detail }, None);
581                        continue;
582                    }
583                },
584            };
585            if !self.used.contains(&style.name) {
586                self.used.push(style.name.clone());
587            }
588            resolved.push((effect, style.name.clone()));
589        }
590        resolved
591    }
592
593    // --- placements, mappings, ranges, indices -----------------------------------------------
594
595    /// A placement: `COL` or `ROW;COL`.
596    fn placement(&self, content: NodeSlice<'t, Flm>) -> Result<Result<Rect, Bad>, LowerError> {
597        let pieces = match pieces(content)? {
598            Ok(pieces) => pieces,
599            Err(bad) => return Ok(Err(bad)),
600        };
601        let parts = split_pieces(pieces, ';');
602        let (row, col) = match parts.as_slice() {
603            [col] => (Vec::new(), col.clone()),
604            [row, col] => (row.clone(), col.clone()),
605            _ => return Ok(Err(Bad(String::from("A cell's placement must be written ‘COL’ or ‘ROW;COL’")))),
606        };
607        let row = match self.placement_index(&row, Axis::Row)? {
608            Ok(span) => span,
609            Err(bad) => return Ok(Err(bad)),
610        };
611        let col = match self.placement_index(&col, Axis::Col)? {
612            Ok(span) => span,
613            Err(bad) => return Ok(Err(bad)),
614        };
615        Ok(Ok(Rect { row, col }))
616    }
617
618    /// One side of a placement: empty for the current index, else an index or
619    /// a `\merge`.
620    fn placement_index(&self, part: &[Piece<'t>], axis: Axis) -> Result<Result<Span, Bad>, LowerError> {
621        if part.is_empty() {
622            let current = self.current(axis);
623            return Ok(Ok((current, Some(current + 1))));
624        }
625        let shown: Vec<&Piece<'t>> = part.iter().filter(|piece| !piece.is_blank()).collect();
626        let [one] = shown.as_slice() else {
627            return Ok(Err(Bad(format!(
628                "A cell's {} must be one number, name, ‘.’ or ‘\\merge{{…}}’",
629                axis.word()
630            ))));
631        };
632        Ok(match one {
633            Piece::Merge(merge) => {
634                let text = match merge_range(merge)? {
635                    Ok(text) => text,
636                    Err(bad) => return Ok(Err(bad)),
637                };
638                match self.range(&text, axis, IndexDefault::Current, Some(0), None) {
639                    Ok((Some(start), end)) => Ok((start, end)),
640                    Ok((None, _)) => Err(Bad(format!("The range ‘{text}’ must give its start"))),
641                    Err(bad) => Err(bad),
642                }
643            }
644            Piece::Text(text) => match self.index(text, axis, IndexDefault::Current) {
645                Ok(Some(index)) => Ok((index, Some(index + 1))),
646                Ok(None) => {
647                    Err(Bad(format!("The {} ‘{}’ must be given", axis.word(), text.trim_matches(is_space))))
648                }
649                Err(bad) => Err(bad),
650            },
651        })
652    }
653
654    /// A mapping: `COLS` or `ROWS;COLS`.
655    fn mapping(&self, content: NodeSlice<'t, Flm>) -> Result<Result<Mapping, Bad>, LowerError> {
656        let pieces = match pieces(content)? {
657            Ok(pieces) => pieces,
658            Err(bad) => return Ok(Err(bad)),
659        };
660        let parts = split_pieces(pieces, ';');
661        let (rows, cols) = match parts.as_slice() {
662            [cols] => (Vec::new(), cols.clone()),
663            [rows, cols] => (rows.clone(), cols.clone()),
664            _ => {
665                return Ok(Err(Bad(String::from(
666                    "The mapping of ‘\\celldata’ must be written ‘COLS’ or ‘ROWS;COLS’",
667                ))));
668            }
669        };
670        let rows = match self.mapping_axis(rows, Axis::Row)? {
671            Ok(spans) => spans,
672            Err(bad) => return Ok(Err(bad)),
673        };
674        let cols = match self.mapping_axis(cols, Axis::Col)? {
675            Ok(spans) => spans,
676            Err(bad) => return Ok(Err(bad)),
677        };
678        Ok(Ok(Mapping { rows, cols }))
679    }
680
681    /// One side of a mapping: a comma-separated list of indices, ranges and
682    /// `\merge`s, each range one entry per index but a `\merge`, which is one
683    /// entry spanning them; nothing for "from the current index on".
684    fn mapping_axis(&self, part: Vec<Piece<'t>>, axis: Axis) -> Result<Result<Vec<Span>, Bad>, LowerError> {
685        if part.is_empty() {
686            return Ok(Ok(Vec::new()));
687        }
688        let mut spans: Vec<Span> = Vec::new();
689        let mut current: Option<u64> = Some(0);
690        for entry in split_pieces(part, ',') {
691            if spans.last().is_some_and(|last| last.1.is_none()) {
692                return Ok(Err(Bad(format!("Only the last {} range of a mapping may be left open", axis.word()))));
693            }
694            let shown: Vec<&Piece<'t>> = entry.iter().filter(|piece| !piece.is_blank()).collect();
695            let [one] = shown.as_slice() else {
696                return Ok(Err(Bad(format!(
697                    "Each {} of a mapping must be one index, range or ‘\\merge{{…}}’",
698                    axis.word()
699                ))));
700            };
701            let (text, merged) = match one {
702                Piece::Merge(merge) => match merge_range(merge)? {
703                    Ok(text) => (text, true),
704                    Err(bad) => return Ok(Err(bad)),
705                },
706                Piece::Text(text) => (text.clone(), false),
707            };
708            let (start, end) = match self.range(&text, axis, IndexDefault::Value(current), current, None) {
709                Ok((Some(start), end)) => (start, end),
710                Ok((None, _)) => {
711                    let written = text.trim_matches(is_space);
712                    return Ok(Err(Bad(format!("The range ‘{written}’ must give its start"))));
713                }
714                Err(bad) => return Ok(Err(bad)),
715            };
716            // The length is counted from the range before any entry is
717            // listed: a mapping may name ranges whose indices, listed one per
718            // entry, would not fit in memory.
719            let entries = match end {
720                Some(end) if !merged => end - start,
721                _ => 1,
722            };
723            if spans.len() as u64 + entries > MAX_CELLS_POSITIONS {
724                return Ok(Err(Bad(format!(
725                    "The mapping of ‘\\celldata’ may list at most {MAX_CELLS_POSITIONS} {}s",
726                    axis.word()
727                ))));
728            }
729            match end {
730                Some(end) if !merged => {
731                    spans.extend((start..end).map(|index| (index, Some(index + 1))));
732                }
733                end => spans.push((start, end)),
734            }
735            current = end;
736        }
737        Ok(Ok(spans))
738    }
739
740    /// A range: `2-4`, `2+3`, `1,2,3`, or a single index; an end of `None` is
741    /// left open.
742    fn range(
743        &self,
744        text: &str,
745        axis: Axis,
746        default: IndexDefault,
747        default_start: Option<u64>,
748        default_end: Option<u64>,
749    ) -> Result<(Option<u64>, Option<u64>), Bad> {
750        // The range as a message quotes it.
751        let written = text.trim_matches(is_space);
752        if text.contains(',') {
753            let mut covered: Vec<(u64, u64)> = Vec::new();
754            for part in text.split(',') {
755                match self.range(part, axis, default, None, None)? {
756                    (Some(start), Some(end)) => covered.push((start, end)),
757                    _ => return Err(Bad(format!("Each part of the range ‘{written}’ must give both its ends"))),
758                }
759            }
760            covered.sort_unstable();
761            let start = covered[0].0;
762            let mut end = covered[0].1;
763            for &(part_start, part_end) in &covered[1..] {
764                if part_start > end {
765                    return Err(Bad(format!("The range ‘{written}’ must be contiguous")));
766                }
767                end = end.max(part_end);
768            }
769            return Ok((Some(start), Some(end)));
770        }
771        if let Some((start, end)) = text.split_once('-') {
772            let start = self.index(start, axis, IndexDefault::Value(default_start))?;
773            let end = match self.index(end, axis, IndexDefault::Value(None))? {
774                Some(last) => Some(last + 1),
775                None => default_end,
776            };
777            if matches!((start, end), (Some(start), Some(end)) if end <= start) {
778                return Err(Bad(format!("The range ‘{written}’ may not run backwards")));
779            }
780            return Ok((start, end));
781        }
782        if let Some((start, count)) = text.split_once('+') {
783            let start = self.index(start, axis, default)?;
784            let count = count.trim_matches(is_space);
785            if count.is_empty() || !count.bytes().all(|byte| byte.is_ascii_digit()) {
786                return Err(Bad(format!("In the range ‘{written}’, ‘{count}’ must be a number")));
787            }
788            let count: u64 = count.parse().unwrap_or(u64::MAX);
789            if count == 0 {
790                return Err(Bad(format!("The range ‘{written}’ must span one {} at least", axis.word())));
791            }
792            let Some(start) = start else {
793                return Err(Bad(format!("The range ‘{written}’ must give its start")));
794            };
795            let end = start.saturating_add(count);
796            if end > MAX_CELLS_POSITIONS {
797                return Err(Bad(format!(
798                    "Invalid range ‘{written}’: a {} number may be at most {MAX_CELLS_POSITIONS}",
799                    axis.word()
800                )));
801            }
802            return Ok((Some(start), Some(end)));
803        }
804        let index = self.index(text, axis, default)?;
805        Ok((index, index.map(|index| index + 1)))
806    }
807
808    /// An index: a number from 1, a declared name, or `.` or nothing for what
809    /// `default` says.
810    fn index(&self, text: &str, axis: Axis, default: IndexDefault) -> Result<Option<u64>, Bad> {
811        let text = text.trim_matches(is_space);
812        if text.is_empty() || text == "." {
813            return Ok(match default {
814                IndexDefault::Current => Some(self.current(axis)),
815                IndexDefault::Value(value) => value,
816            });
817        }
818        if text.bytes().all(|byte| byte.is_ascii_digit()) {
819            let number: u64 = text.parse().unwrap_or(u64::MAX);
820            if number == 0 {
821                return Err(Bad(format!("A {} number must be 1 or more, not 0", axis.word())));
822            }
823            if number > MAX_CELLS_POSITIONS {
824                return Err(Bad(format!(
825                    "Invalid {word} number ‘{text}’: a {word} number may be at most {MAX_CELLS_POSITIONS}",
826                    word = axis.word()
827                )));
828            }
829            return Ok(Some(number - 1));
830        }
831        match self.names[axis.index()].get(text) {
832            Some(&index) => Ok(Some(index)),
833            None => Err(Bad(format!(
834                "‘{text}’ is not a {word} number or a declared {word} name",
835                word = axis.word()
836            ))),
837        }
838    }
839
840    // --- the second pass and the grid --------------------------------------------------------
841
842    fn finish(mut self, node: &NodeRef<'t, Flm>) -> Grid<'t> {
843        let [rows, cols] = self.size;
844        let mut held: Vec<Option<(u64, u64)>> = vec![None; (rows * cols) as usize];
845        let mut accepted: Vec<(CellSpec, CellContent<'t>)> = Vec::new();
846        let cells = std::mem::take(&mut self.cells);
847        for (order, placed) in cells {
848            let rect = placed.rect;
849            let row = (rect.row.0, rect.row.1.unwrap_or(rows));
850            let col = (rect.col.0, rect.col.1.unwrap_or(cols));
851            let overlapped = (row.0..row.1)
852                .flat_map(|r| (col.0..col.1).map(move |c| (r, c)))
853                .find_map(|(r, c)| held[(r * cols + c) as usize]);
854            if let Some((earlier_row, earlier_col)) = overlapped {
855                self.order = order;
856                let dropped = DroppedPayload {
857                    condition: Name::from("flm.cells.overlap"),
858                    detail: String::from("cell overlapping another"),
859                };
860                self.report(&placed.at, Overlap { row: earlier_row + 1, col: earlier_col + 1 }, Some(dropped));
861                continue;
862            }
863            for r in row.0..row.1 {
864                for c in col.0..col.1 {
865                    held[(r * cols + c) as usize] = Some((row.0, col.0));
866                }
867            }
868            let mut spec = CellSpec::at(row.0 as u32, col.0 as u32);
869            spec.row_span = (row.1 - row.0) as u32;
870            spec.col_span = (col.1 - col.0) as u32;
871            apply(&mut spec, &placed.styles);
872            accepted.push((spec, placed.content));
873        }
874        if accepted.is_empty() {
875            self.order = u64::MAX;
876            self.report(node, Empty, None);
877        }
878        accepted.sort_by_key(|(spec, _)| (spec.row, spec.col));
879        let (specs, contents): (Vec<CellSpec>, Vec<CellContent<'t>>) = accepted.into_iter().unzip();
880        let mut problems = self.problems;
881        problems.sort_by_key(|found| found.order);
882        Grid {
883            payload: CellsPayload { rows: rows as u32, cols: cols as u32, cells: specs },
884            contents,
885            problems: problems.into_iter().map(|found| found.problem).collect(),
886            styles: self.used,
887        }
888    }
889}
890
891/// Writes the facts of the resolved tokens into a cell's entry: the first
892/// alignment and the first header kind decide; every edge line and every
893/// custom style is kept once, in order.
894fn apply(spec: &mut CellSpec, styles: &[Resolved]) {
895    for (effect, name) in styles {
896        match *effect {
897            Effect::Align(align) => {
898                spec.align.get_or_insert(align);
899            }
900            Effect::Header(header) => {
901                spec.header.get_or_insert(header);
902            }
903            Effect::Rule(edge) => {
904                if !spec.rules.contains(&edge) {
905                    spec.rules.push(edge);
906                }
907            }
908            Effect::Custom => {
909                if !spec.styles.contains(name) {
910                    spec.styles.push(name.clone());
911                }
912            }
913        }
914    }
915}
916
917/// Returns `values` for a message: each value between quotation marks, the
918/// values separated by commas.
919fn quoted(values: &[&str]) -> String {
920    values.iter().map(|value| format!("‘{value}’")).collect::<Vec<_>>().join(", ")
921}
922
923/// Whether `text` is a name of a row or a column: an ASCII letter, then ASCII
924/// letters, digits and underscores.
925fn is_name(text: &str) -> bool {
926    let mut chars = text.chars();
927    chars.next().is_some_and(|first| first.is_ascii_alphabetic())
928        && chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
929}
930
931/// Whether `node` is a comment or blank, in the lowering helpers' sense
932/// ([`is_blank`]): whitespace text, or a node that is whitespace, such as `~`.
933fn is_comment_or_blank(node: &NodeRef<'_, Flm>) -> bool {
934    node.is_comment() || is_blank(node)
935}
936
937/// An empty run of nodes of `node`'s tree.
938fn empty_slice<'t>(node: &NodeRef<'t, Flm>) -> NodeSlice<'t, Flm> {
939    let at = node.id().index() as u32;
940    node.tree().slice(at..at).expect("an empty range of the tree")
941}
942
943/// The runs of `content` between its top-level nodes of the element
944/// `separator`, as str::split cuts a string: one more run than there are
945/// separators.
946fn split<'t>(content: NodeSlice<'t, Flm>, separator: &str) -> Vec<NodeSlice<'t, Flm>> {
947    let range = content.range();
948    let tree = content.first().map(|node| node.tree());
949    let Some(tree) = tree else { return vec![content] };
950    let mut runs = Vec::new();
951    let mut start = range.start;
952    for (k, node) in content.iter().enumerate() {
953        let at = range.start + k as u32;
954        if node.is_callable() && element_of(&node).name.as_str() == separator {
955            runs.push(tree.slice(start..at).expect("a run of siblings"));
956            start = at + 1;
957        }
958    }
959    runs.push(tree.slice(start..range.end).expect("a run of siblings"));
960    runs
961}
962
963/// The pieces of a placement or a mapping: runs of characters and `\merge`s,
964/// comments skipped. Anything else is an argument that cannot be read.
965fn pieces<'t>(content: NodeSlice<'t, Flm>) -> Result<Result<Vec<Piece<'t>>, Bad>, LowerError> {
966    let mut pieces = Vec::new();
967    let mut run: Vec<NodeRef<'t, Flm>> = Vec::new();
968    let flush = |run: &mut Vec<NodeRef<'t, Flm>>, pieces: &mut Vec<Piece<'t>>| -> Result<Result<(), Bad>, LowerError> {
969        if run.is_empty() {
970            return Ok(Ok(()));
971        }
972        let read = chars_at_lowering(std::mem::take(run))?;
973        Ok(match read {
974            Ok(text) => {
975                pieces.push(Piece::Text(text));
976                Ok(())
977            }
978            Err(_) => Err(Bad(String::from(
979                "A placement or a mapping may hold only numbers, names, ranges and ‘\\merge{…}’",
980            ))),
981        })
982    };
983    for node in content.iter() {
984        if node.is_comment() {
985            continue;
986        }
987        if node.is_callable() && element_of(&node).name.as_str() == MERGE {
988            if let Err(bad) = flush(&mut run, &mut pieces)? {
989                return Ok(Err(bad));
990            }
991            pieces.push(Piece::Merge(node));
992        } else {
993            run.push(node);
994        }
995    }
996    if let Err(bad) = flush(&mut run, &mut pieces)? {
997        return Ok(Err(bad));
998    }
999    Ok(Ok(pieces))
1000}
1001
1002/// The pieces cut at every `separator` among their characters, as str::split
1003/// cuts a string.
1004fn split_pieces<'t>(pieces: Vec<Piece<'t>>, separator: char) -> Vec<Vec<Piece<'t>>> {
1005    let mut parts: Vec<Vec<Piece<'t>>> = vec![Vec::new()];
1006    for piece in pieces {
1007        match piece {
1008            Piece::Text(text) => {
1009                for (k, segment) in text.split(separator).enumerate() {
1010                    if k > 0 {
1011                        parts.push(Vec::new());
1012                    }
1013                    if !segment.is_empty() {
1014                        parts.last_mut().expect("a part").push(Piece::Text(segment.to_string()));
1015                    }
1016                }
1017            }
1018            merge => parts.last_mut().expect("a part").push(merge),
1019        }
1020    }
1021    parts
1022}
1023
1024/// The range a `\merge` gives, read as characters.
1025fn merge_range(merge: &NodeRef<'_, Flm>) -> Result<Result<String, Bad>, LowerError> {
1026    let Ok(Some(content)) = merge.argument_content_nodes_named(RANGE_ARG) else { return Ok(Ok(String::new())) };
1027    Ok(match chars_at_lowering(content.iter())? {
1028        Ok(text) => Ok(text),
1029        Err(_) => Err(Bad(String::from("The range of ‘\\merge’ may hold only numbers, names and range signs"))),
1030    })
1031}
1032
1033#[cfg(test)]
1034mod tests {
1035    use super::*;
1036
1037    #[test]
1038    fn a_mapping_entry_is_its_own_the_open_range_continued_or_the_last_repeated() {
1039        let spans = [(0, Some(1)), (2, Some(3))];
1040        assert_eq!(Mapping::get(&spans, 0, 9), (0, Some(1)));
1041        assert_eq!(Mapping::get(&spans, 1, 9), (2, Some(3)));
1042        assert_eq!(Mapping::get(&spans, 5, 9), (2, Some(3)));
1043        let open = [(0, Some(1)), (1, Some(2)), (2, None)];
1044        assert_eq!(Mapping::get(&open, 2, 9), (2, Some(3)));
1045        assert_eq!(Mapping::get(&open, 4, 9), (4, Some(5)));
1046        assert_eq!(Mapping::get(&[], 3, 7), (7, Some(8)));
1047    }
1048
1049    #[test]
1050    fn a_name_is_a_letter_then_letters_digits_and_underscores() {
1051        assert!(is_name("height"));
1052        assert!(is_name("row_2"));
1053        assert!(!is_name("1x"));
1054        assert!(!is_name("a-b"));
1055        assert!(!is_name(""));
1056    }
1057}