Skip to main content

flm_core/stdlib/features/cells/
elements.rs

1//! The eight elements of the tables of cells, their element declarations,
2//! the feature's four scoped packages
3//! ([`ScopedPackageDef`]; see
4//! [scoped packages](crate::guide::concepts_overview#scoped-packages)), and
5//! the predicate that decides the block role of four of the commands
6//! ([`stands_in_body`], [`InBody`]).
7
8use std::sync::Arc;
9
10use techy::core::node::NodeRef;
11
12use crate::lang::mint::{ArgDef, ArgLayout, ArgStdKind, BodyDef, ElementDef, ScopedPackageDef, SyntaxDef};
13use crate::lang::Flm;
14use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
15use crate::model::element::{ElementSpec, element_of};
16use crate::model::names::{FeatureName, Name};
17use crate::stdlib::backends::lowering::rules::owning_callable;
18
19use super::parser::CellStylesParser;
20use super::{
21    BODY_PACKAGE, CELL, COLNAMES, COLUMN, CONTENT_ARG, DATA, DATA_ARG, DATA_PACKAGE, ENVIRONMENT,
22    ENVIRONMENT_PACKAGE, MAPPING_ARG, MERGE, MERGE_PACKAGE, NAMES_ARG, PLACEMENT_ARG, RANGE_ARG, ROW,
23    ROWNAMES, STYLES_ARG,
24};
25
26/// Whether `node` is a direct child of the body of a `cells` environment:
27/// its owner, the command or environment of whose body it is a direct child,
28/// is an element named [`ENVIRONMENT`] (`flm.cells.cells`).
29///
30/// This predicate decides the block role of `\cell`, `\\`, `\rownames` and
31/// `\colnames` ([`InBody`]). The table's reader
32/// ([`read_grid`](super::read_grid)) does not call it, but reads the body's
33/// direct children as its instructions, which are exactly the nodes for
34/// which this predicate is true, so the block role and the reading cannot
35/// disagree. The predicate reads the tree each time; nothing is stored.
36pub fn stands_in_body(node: &NodeRef<'_, Flm>) -> bool {
37    owning_callable(node).is_some_and(|owner| element_of(&owner).name.as_str() == ENVIRONMENT)
38}
39
40/// The block role of `\cell`, `\\`, `\rownames` and `\colnames`, decided by
41/// position. The command is a block where it is a direct child of the body
42/// of a `cells` environment ([`stands_in_body`]), as one of the table's
43/// instructions. It is inline content everywhere else: inside the data of a
44/// `\celldata`, where it is an entry's cell or ends a row, and inside a
45/// cell's content, where it is out of place and reported when lowered
46/// ([`OutsideTable`](super::diagnostics::OutsideTable)).
47#[derive(Debug, Default, Clone, Copy)]
48pub struct InBody;
49
50impl BlockRoleAspect for InBody {
51    fn block_role(&self, node: &NodeRef<'_, Flm>) -> BlockRole {
52        if stands_in_body(node) { BlockRole::Block } else { BlockRole::DEFAULT }
53    }
54}
55
56/// An element value whose block role is decided by position ([`InBody`]).
57fn by_position(name: &str, docs: &str) -> Arc<ElementSpec> {
58    Arc::new(ElementSpec::new(name).docs(docs).with::<dyn BlockRoleAspect>(Arc::new(InBody)))
59}
60
61/// An element value that is always a block.
62fn block(name: &str, docs: &str) -> Arc<ElementSpec> {
63    Arc::new(
64        ElementSpec::new(name)
65            .docs(docs)
66            .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::Block))),
67    )
68}
69
70/// An element value that is always inline content, the default block
71/// role.
72fn inline(name: &str, docs: &str) -> Arc<ElementSpec> {
73    Arc::new(ElementSpec::new(name).docs(docs))
74}
75
76/// The element value of the environment, shared by its two declarations
77/// (in the scoped package, and as an ordinary environment under
78/// [`CellsConfig::global`](super::CellsConfig::global)): a block.
79pub(super) fn environment_spec() -> Arc<ElementSpec> {
80    block(ENVIRONMENT, "`\\begin{cells}…\\end{cells}`: a table of cells.")
81}
82
83/// One declaration of the environment `cells`, carrying `spec`: no argument,
84/// and a body laid out as blocks that refers to the scoped package
85/// [`BODY_PACKAGE`].
86pub(super) fn environment_def(owner: &FeatureName, spec: &Arc<ElementSpec>) -> ElementDef {
87    ElementDef::new(
88        owner.clone(),
89        ["cells"],
90        SyntaxDef::Environment { args: Vec::new(), body: BodyDef::new().blocks().scoped(BODY_PACKAGE) },
91        Arc::clone(spec),
92    )
93    .docs(
94        "Writes a table of cells, filled with `\\cell`, `\\celldata` and `\\\\`, its rows and \
95         columns optionally named with `\\rownames` and `\\colnames`.",
96    )
97}
98
99/// The styles argument of `\cell` and `\celldata`: an optional `<…>` group
100/// ([`CellStylesParser`]).
101fn styles_arg() -> ArgDef {
102    ArgDef::named(STYLES_ARG, CellStylesParser::new())
103        .docs("Style tokens, separated by whitespace: a name, or a name with a value in braces.")
104}
105
106/// The commands of the body: `\cell`, `\celldata`, `\\`, `\rownames` and
107/// `\colnames`.
108fn body_commands(owner: &FeatureName) -> Vec<ElementDef> {
109    let cell = ElementDef::new(
110        owner.clone(),
111        ["cell"],
112        SyntaxDef::Macro {
113            args: vec![
114                styles_arg(),
115                ArgDef::named(PLACEMENT_ARG, ArgStdKind::Optional).scoped(MERGE_PACKAGE).docs(
116                    "Where the cell goes: `COL` or `ROW;COL`, each a number, a name, `.` or empty for \
117                     the current one, or `\\merge{RANGE}` for a span.",
118                ),
119                ArgDef::named(CONTENT_ARG, ArgStdKind::Mandatory)
120                    .layout(ArgLayout::Blocks)
121                    .docs("The cell's content: paragraphs and blocks."),
122            ],
123        },
124        by_position(CELL, "`\\cell<styles>[placement]{content}`: one cell of a table of cells."),
125    )
126    .docs("Adds a cell to the table, in the next column of the current row by default.");
127    let data = ElementDef::new(
128        owner.clone(),
129        ["celldata"],
130        SyntaxDef::Macro {
131            args: vec![
132                styles_arg(),
133                ArgDef::named(MAPPING_ARG, ArgStdKind::Optional).scoped(MERGE_PACKAGE).docs(
134                    "Where the data goes: `COLS` or `ROWS;COLS`, each a comma-separated list of \
135                     indices, ranges and `\\merge{RANGE}`.",
136                ),
137                ArgDef::named(DATA_ARG, ArgStdKind::Mandatory)
138                    .layout(ArgLayout::Inline)
139                    .scoped(DATA_PACKAGE)
140                    .docs("Rows ended by `\\\\`, entries separated by `&`; each entry inline content."),
141            ],
142        },
143        block(DATA, "`\\celldata<styles>[mapping]{data}`: several cells of a table of cells, by rows."),
144    )
145    .docs("Adds a cell per entry of the data, row by row.");
146    let row = ElementDef::new(
147        owner.clone(),
148        ["\\"],
149        SyntaxDef::Macro { args: Vec::new() },
150        by_position(ROW, "`\\\\` in a table of cells: the next cell starts a new row."),
151    )
152    .docs("Starts a new row: the next cell goes into it.");
153    let names = |command: &str, element: &str, what: &str| {
154        ElementDef::new(
155            owner.clone(),
156            [command],
157            SyntaxDef::Macro {
158                args: vec![ArgDef::named(NAMES_ARG, ArgStdKind::CharsGroup).docs(format!(
159                    "Comma-separated names; the k-th is the name of {what} k, and an empty entry \
160                     gives no name."
161                ))],
162            },
163            by_position(element, &format!("`\\{command}{{names}}`: names for the {what}s of a table of cells.")),
164        )
165        .docs(format!("Names the {what}s, so that a name can be written wherever a {what} number can."))
166    };
167    vec![cell, data, row, names("rownames", ROWNAMES, "row"), names("colnames", COLNAMES, "column")]
168}
169
170/// The feature's four scoped packages: the environment's
171/// ([`ENVIRONMENT_PACKAGE`]), the body's ([`BODY_PACKAGE`]), the placements'
172/// and mappings' ([`MERGE_PACKAGE`]) and the data's ([`DATA_PACKAGE`]).
173pub(super) fn packages(owner: &FeatureName, environment: &Arc<ElementSpec>) -> Vec<ScopedPackageDef> {
174    let merge = ElementDef::new(
175        owner.clone(),
176        ["merge"],
177        SyntaxDef::Macro {
178            args: vec![ArgDef::named(RANGE_ARG, ArgStdKind::CharsGroup).docs(
179                "The rows or columns the cell spans: `2-4`, `2+3`, `1,2,3`, a start or an end left out.",
180            )],
181        },
182        inline(MERGE, "`\\merge{range}`: a span of rows or of columns, in a cell's placement."),
183    )
184    .docs("Gives the rows or the columns a cell spans.");
185    let column = ElementDef::new(
186        owner.clone(),
187        Vec::<Name>::new(),
188        SyntaxDef::Specials { trigger: String::from("&"), args: Vec::new() },
189        inline(COLUMN, "`&` in the data of `\\celldata`: the end of an entry."),
190    )
191    .docs("Ends an entry of the data.");
192    vec![
193        ScopedPackageDef {
194            owner: owner.clone(),
195            name: Name::from(ENVIRONMENT_PACKAGE),
196            elements: vec![environment_def(owner, environment)],
197            docs: String::from("The `cells` environment, in the bodies that accept a table of cells."),
198        },
199        ScopedPackageDef {
200            owner: owner.clone(),
201            name: Name::from(BODY_PACKAGE),
202            elements: body_commands(owner),
203            docs: String::from(
204                "The instructions of a table of cells: `\\cell`, `\\celldata`, `\\\\`, `\\rownames` and \
205                 `\\colnames`.",
206            ),
207        },
208        ScopedPackageDef {
209            owner: owner.clone(),
210            name: Name::from(MERGE_PACKAGE),
211            elements: vec![merge],
212            docs: String::from("`\\merge`, in the placement of a cell and the mapping of `\\celldata`."),
213        },
214        ScopedPackageDef {
215            owner: owner.clone(),
216            name: Name::from(DATA_PACKAGE),
217            elements: vec![column],
218            docs: String::from("`&`, in the data of `\\celldata`."),
219        },
220    ]
221}