flm_core/lang/structural.rs
1//! The structural elements of the language, and their stable names.
2//!
3//! The structural elements are the elements of the node shapes no feature
4//! declares: text, comments, containers, groups of each class, paragraphs,
5//! paragraph breaks, template placeholders, the fields a construct absorbs as
6//! data (`flm.field`), and the macros and environments a parse could not
7//! attribute to any feature (`flm.unknown.macro`,
8//! `flm.unknown.environment`); there is one element value per shape. See
9//! [structural elements](crate::guide::concepts_overview#structural-elements).
10//!
11//! Every node of an FLM tree carries an
12//! [element](crate::model::element::ElementSpec), the value that says what the
13//! node means. A node written as a macro, an environment or a special character
14//! sequence of a feature takes its element from the specification it resolved
15//! to. Every other node takes its element from the structural elements, so
16//! every node has an element and finding it needs no lookup by name.
17//!
18//! A set of structural elements is one [`StructuralElements`] value. The
19//! parsing state carries it in its extension
20//! ([`FlmStateExt::structural`](crate::lang::FlmStateExt::structural)), and
21//! [`resolve_element`](crate::lang::mint::resolve_element) reads it there. The
22//! registry builds the set through [`StructuralElementSpecs`]: it starts from
23//! the default set, lets features attach [aspects](crate::model::aspects) to
24//! any of the elements (they are ordinary element values), and freezes the
25//! result with [`StructuralElements::new`]. The language build then installs
26//! the frozen set in the parsing state every parse starts from.
27//!
28//! The constants of this module ([`TEXT`], [`COMMENT`], …, listed in [`NAMES`])
29//! are the elements' stable names: a name identifies the element, and a
30//! serialized tree records it.
31
32use std::sync::Arc;
33
34use techy::core::node::NodeRef;
35use techy::latexlike::MathGroupForm;
36
37use crate::lang::Flm;
38use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
39use crate::model::element::ElementSpec;
40use crate::model::names::ElementName;
41
42/// The name of the element of a text node, a run of characters: `flm.text`.
43pub const TEXT: &str = "flm.text";
44/// The name of the element of a source comment node: `flm.comment`.
45pub const COMMENT: &str = "flm.comment";
46/// The name of the element of a list node, a container that holds content
47/// without meaning anything itself (a tree's root, an environment's body, an
48/// argument that holds several nodes): `flm.container`.
49pub const CONTAINER: &str = "flm.container";
50/// The name of the element of a `{…}` content group, and of any group the
51/// library creates without a group class: `flm.group`.
52pub const GROUP: &str = "flm.group";
53/// The name of the element of a mathematics group (`\(…\)`, `\[…\]`, and
54/// `$…$` where `$` is enabled as a delimiter): `flm.math`. Whether the group is
55/// inline or display mathematics is recorded in the node's group class
56/// ([`FlmGroupType::Math`](crate::lang::FlmGroupType::Math)), not in its
57/// element.
58pub const MATH: &str = "flm.math";
59/// The name of the element of a verbatim group, the group node that is the
60/// parent of every run of raw text: `flm.verbatim`. See [verbatim
61/// regions](crate::guide::concepts_overview#verbatim-regions).
62pub const VERBATIM: &str = "flm.verbatim";
63/// The name of the element of an opaque wrapper, the group with no delimiters
64/// of its own that holds parsed content kept as written
65/// ([`FlmGroupType::OpaqueWrapper`](crate::lang::FlmGroupType::OpaqueWrapper)):
66/// `flm.opaque-wrapper`. Every backend writes it natively, through its
67/// children.
68pub const OPAQUE_WRAPPER: &str = "flm.opaque-wrapper";
69/// The name of the element of a paragraph: `flm.paragraph`. Paragraphs are
70/// created by the block-structure rewrite pass
71/// ([`crate::lang::rewrites::blocks`]); no delimiter in the source opens one.
72pub const PARAGRAPH: &str = "flm.paragraph";
73/// The name of the element of a paragraph-break node, which the parse creates
74/// for a blank line: `flm.parbreak`. The block-structure rewrite pass
75/// recognizes the node by this element and splits paragraphs there.
76pub const PARBREAK: &str = "flm.parbreak";
77/// The name of the element of a placeholder node, the place in a [user
78/// definition](crate::lang::rewrites::userdefs::Definition)'s template where the
79/// content of one of its arguments is inserted: `flm.placeholder`.
80pub const PLACEHOLDER: &str = "flm.placeholder";
81/// The name of the element of a field node: `flm.field`.
82///
83/// A [field](crate::guide::concepts_overview#fields-data-a-construct-reads)
84/// is a macro that a construct absorbs as data rather than as content, such
85/// as the `\label{sec:intro}` written after `\section{Introduction}`. A
86/// construct accepts its fields through its tack-on argument
87/// ([`ArgStdKind::TackOn`](crate::lang::mint::ArgStdKind::TackOn)), which
88/// lists them as [tack-on fields](crate::lang::mint::TackOnField): each field
89/// node it absorbs is a macro node, named as the field is written, that
90/// carries this element. A field may also be a macro of a [scoped
91/// package](crate::lang::mint::ScopedPackageDef), whose declaration gives it an
92/// element value of the same name
93/// ([`field_element`](crate::lang::mint::field_element)). The construct that
94/// declared a field reads its node by the name it is written with
95/// ([`field_name`](crate::lang::mint::field_name)); see the
96/// [`field`](crate::lang::mint::field) module.
97///
98/// A field node that reaches a backend's lowering is reported as an error
99/// ([`FieldRule`](crate::stdlib::backends::lowering::FieldRule)): the
100/// construct that absorbed it did not read its data.
101pub const FIELD: &str = "flm.field";
102/// The name of the element of a macro the parse could not attribute to any
103/// feature (`\foo` where nothing defines `foo`): `flm.unknown.macro`. Such a
104/// node always comes with an error diagnostic.
105///
106/// The language's own macro fallback, at the bottom of the scope stack,
107/// resolves such a name in every parsing mode; a fallback that a feature
108/// declares (for example a mathematics feature's, in mathematics mode) takes
109/// precedence wherever one exists. The node takes no argument and records the
110/// escape character and the name as written, so that a backend can print the
111/// macro back unchanged.
112///
113/// A document can contain such a node, so this element is among the registry's
114/// [elements that can occur in a
115/// document](crate::core::registry::FlmRegistry::occurrable_elements), and
116/// building a plan requires a lowering rule for it on each backend, like any
117/// other element.
118pub const UNKNOWN_MACRO: &str = "flm.unknown.macro";
119/// The name of the element of an environment the parse could not attribute to
120/// any feature (`\begin{foo}…\end{foo}` where nothing defines `foo`):
121/// `flm.unknown.environment`. Such a node always comes with an error
122/// diagnostic.
123///
124/// Like an unknown macro ([`UNKNOWN_MACRO`]), such an environment is resolved by
125/// the language's own fallback in every parsing mode, below every fallback a
126/// feature declares. Its body is parsed and laid out as **block** content,
127/// because an environment usually holds blocks, so a blank line inside it
128/// becomes a paragraph break and causes no further diagnostic.
129///
130/// Like [`UNKNOWN_MACRO`], it is among the registry's [elements that can occur
131/// in a document](crate::core::registry::FlmRegistry::occurrable_elements) and
132/// needs a lowering rule on each backend.
133pub const UNKNOWN_ENVIRONMENT: &str = "flm.unknown.environment";
134
135/// Every structural element name, in the fixed order in which the set is
136/// listed. [`StructuralElements::all`] returns the elements in the same order.
137pub const NAMES: [&str; 13] = [
138 TEXT,
139 COMMENT,
140 CONTAINER,
141 GROUP,
142 MATH,
143 VERBATIM,
144 OPAQUE_WRAPPER,
145 PARAGRAPH,
146 PARBREAK,
147 PLACEHOLDER,
148 FIELD,
149 UNKNOWN_MACRO,
150 UNKNOWN_ENVIRONMENT,
151];
152
153/// The documentation text the language gives to the structural element type
154/// `name`, one of [`NAMES`]: what the nodes of that type mean, whatever their
155/// element value. `None` for any other name.
156///
157/// The registry holds these texts with the texts that features give to their
158/// own element types
159/// ([`FlmRegistry::element_type_text`](crate::core::registry::FlmRegistry::element_type_text)),
160/// attributed to the language
161/// ([`LANGUAGE_OWNER`](crate::lang::mint::LANGUAGE_OWNER)). A text is FLM,
162/// written as every documentation text is
163/// ([`ElementDef::docs`](crate::lang::mint::ElementDef::docs)).
164pub(crate) fn type_text(name: &str) -> Option<&'static str> {
165 let text = match name {
166 TEXT => "A run of text characters.",
167 COMMENT => "A comment written in the source, from `%` to the end of the line.",
168 CONTAINER => "A container: content held together, with no meaning of its own.",
169 GROUP => "A content group, written `{…}`.",
170 MATH => {
171 "A mathematics group: inline mathematics, written `\\(…\\)` or `$…$`, or display \
172 mathematics, written `\\[…\\]` or `$$…$$`."
173 }
174 VERBATIM => "A verbatim group: raw text, kept exactly as written.",
175 OPAQUE_WRAPPER => "Parsed content kept as written, in a group with no delimiters.",
176 PARAGRAPH => "A paragraph.",
177 PARBREAK => "A paragraph break: a blank line in the source.",
178 PLACEHOLDER => {
179 "A placeholder of a template, such as `#1` or `#{name}`, replaced by content when \
180 the template is expanded."
181 }
182 FIELD => {
183 "A field: a macro that a construct reads as data, not as content, such as the \
184 `\\label` written after a heading or the `\\tag` written in a line of displayed \
185 equations.\n\nEvery field has this type, \
186 whichever construct declares it; only the construct that declares a field reads it."
187 }
188 UNKNOWN_MACRO => "A macro that no feature of the document defines, reported as an error.",
189 UNKNOWN_ENVIRONMENT => {
190 "An environment that no feature of the document defines, reported as an error; its \
191 body is block content."
192 }
193 _ => return None,
194 };
195 Some(text)
196}
197
198/// The structural elements while they can still be changed: one element value
199/// per node shape, to which the registry attaches the features' aspects before
200/// it freezes the set into a [`StructuralElements`] with
201/// [`StructuralElements::new`].
202///
203/// [`StructuralElementSpecs::default`] is the set FLM starts from. Change an
204/// element with [`get_mut`](Self::get_mut).
205#[derive(Debug, Clone)]
206pub struct StructuralElementSpecs {
207 /// The element of text nodes; inline content. See [`TEXT`].
208 pub text: ElementSpec,
209 /// The element of source comment nodes; inline content, and they render
210 /// nothing. See [`COMMENT`].
211 pub comment: ElementSpec,
212 /// The element of list nodes, containers that hold content without meaning
213 /// anything themselves. See [`CONTAINER`].
214 pub container: ElementSpec,
215 /// The element of content groups, and of groups the library creates
216 /// without a group class; inline content. See [`GROUP`].
217 pub group: ElementSpec,
218 /// The element of mathematics groups; a [displayed
219 /// item](BlockRole::Displayed) for display mathematics (`\[…\]`,
220 /// `$$…$$`) and inline content for inline mathematics (`\(…\)`, `$…$`),
221 /// as its block role aspect reads from the group's form. See [`MATH`].
222 pub math: ElementSpec,
223 /// The element of verbatim groups; inline content. See [`VERBATIM`].
224 pub verbatim: ElementSpec,
225 /// The element of opaque wrappers; inline content, like a verbatim group.
226 /// See [`OPAQUE_WRAPPER`].
227 pub opaque_wrapper: ElementSpec,
228 /// The element of paragraphs; block content. See [`PARAGRAPH`].
229 pub paragraph: ElementSpec,
230 /// The element of paragraph-break nodes. It has no block role: the node
231 /// separates blocks and is not a block. See [`PARBREAK`].
232 pub parbreak: ElementSpec,
233 /// The element of placeholder nodes; no block role. See [`PLACEHOLDER`].
234 pub placeholder: ElementSpec,
235 /// The element of field nodes; inline content. See [`FIELD`].
236 pub field: ElementSpec,
237 /// The element of a macro no feature defines; inline content. See
238 /// [`UNKNOWN_MACRO`].
239 pub unknown_macro: ElementSpec,
240 /// The element of an environment no feature defines; block content. See
241 /// [`UNKNOWN_ENVIRONMENT`].
242 pub unknown_environment: ElementSpec,
243}
244
245impl StructuralElementSpecs {
246 /// Returns the element named `name`, one of [`NAMES`], for modification;
247 /// `None` for any other name. The registry attaches a feature's aspects to
248 /// a structural element through this method, before the set is frozen.
249 pub fn get_mut(&mut self, name: &str) -> Option<&mut ElementSpec> {
250 Some(match name {
251 TEXT => &mut self.text,
252 COMMENT => &mut self.comment,
253 CONTAINER => &mut self.container,
254 GROUP => &mut self.group,
255 MATH => &mut self.math,
256 VERBATIM => &mut self.verbatim,
257 OPAQUE_WRAPPER => &mut self.opaque_wrapper,
258 PARAGRAPH => &mut self.paragraph,
259 PARBREAK => &mut self.parbreak,
260 PLACEHOLDER => &mut self.placeholder,
261 FIELD => &mut self.field,
262 UNKNOWN_MACRO => &mut self.unknown_macro,
263 UNKNOWN_ENVIRONMENT => &mut self.unknown_environment,
264 _ => return None,
265 })
266 }
267}
268
269impl Default for StructuralElementSpecs {
270 /// Returns the set FLM starts from, with a block role
271 /// ([`BlockRoleAspect`]) attached where the node shape has one.
272 ///
273 /// Text, comments, groups, verbatim groups, opaque wrappers, fields and a
274 /// macro no feature defines are inline content. A mathematics group is a
275 /// displayed item or inline content, according to its form
276 /// ([`math`](Self::math)). A paragraph and an environment no feature defines
277 /// are blocks. The paragraph-break node and the placeholder have no block
278 /// role, and neither does the container: the library asks a container's
279 /// children for their roles, not the container, and an element without the
280 /// aspect counts as inline content
281 /// ([`block_role_of`](crate::model::aspects::block_role_of)).
282 fn default() -> StructuralElementSpecs {
283 // Aspects are keyed by their trait object type: every attachment names
284 // `dyn BlockRoleAspect`, never the concrete implementation.
285 let inline = || Arc::new(FixedBlockRole(BlockRole::DEFAULT));
286 let block = || Arc::new(FixedBlockRole(BlockRole::Block));
287 let element = |name: &str, docs: &str| ElementSpec::new(ElementName::from(name)).docs(docs);
288 StructuralElementSpecs {
289 text: element(TEXT, "a run of text characters").with::<dyn BlockRoleAspect>(inline()),
290 comment: element(COMMENT, "a source comment").with::<dyn BlockRoleAspect>(inline()),
291 container: element(
292 CONTAINER,
293 "a container that holds content without meaning anything itself",
294 ),
295 group: element(GROUP, "a `{…}` content group").with::<dyn BlockRoleAspect>(inline()),
296 math: element(MATH, "a mathematics group").with::<dyn BlockRoleAspect>(Arc::new(MathGroupRole)),
297 verbatim: element(VERBATIM, "a verbatim group, the parent of a run of raw text")
298 .with::<dyn BlockRoleAspect>(inline()),
299 opaque_wrapper: element(
300 OPAQUE_WRAPPER,
301 "a group with no delimiters that holds parsed content kept as written",
302 )
303 .with::<dyn BlockRoleAspect>(inline()),
304 paragraph: element(PARAGRAPH, "a paragraph").with::<dyn BlockRoleAspect>(block()),
305 parbreak: element(PARBREAK, "a paragraph break (a blank line in the source)"),
306 placeholder: element(
307 PLACEHOLDER,
308 "a placeholder of a template (`#1`, `#{name}`), replaced by content when the \
309 template is expanded",
310 ),
311 field: element(
312 FIELD,
313 "a field: a macro that a construct absorbs as data, such as the `\\label` written \
314 after a heading; only the construct that declared the field reads it",
315 )
316 .with::<dyn BlockRoleAspect>(inline()),
317 unknown_macro: element(
318 UNKNOWN_MACRO,
319 "a macro the parse could not attribute to any feature, reported as an error",
320 )
321 .with::<dyn BlockRoleAspect>(inline()),
322 unknown_environment: element(
323 UNKNOWN_ENVIRONMENT,
324 "an environment the parse could not attribute to any feature, reported as an \
325 error; its body is block content",
326 )
327 .with::<dyn BlockRoleAspect>(block()),
328 }
329 }
330}
331
332/// The [`BlockRoleAspect`] of the element of mathematics groups, [`MATH`]: a
333/// group of display mathematics, written `\[…\]` or `$$…$$`, is a
334/// [displayed item](BlockRole::Displayed), and a group of inline mathematics,
335/// written `\(…\)` or `$…$`, is ordinary inline content
336/// ([`BlockRole::DEFAULT`]).
337///
338/// The aspect reads the form of the group from the node's group class
339/// ([`FlmGroupType::Math`](crate::lang::FlmGroupType::Math)), where the parse
340/// records it; a node that is no mathematics group has the default role.
341#[derive(Debug)]
342struct MathGroupRole;
343
344impl BlockRoleAspect for MathGroupRole {
345 fn block_role(&self, node: &NodeRef<'_, Flm>) -> BlockRole {
346 match node.math_form() {
347 Some(MathGroupForm::Display) => BlockRole::Displayed,
348 Some(MathGroupForm::Inline) | None => BlockRole::DEFAULT,
349 }
350 }
351}
352
353/// A frozen, shared set of structural elements: one element value per node
354/// shape that no feature declares.
355///
356/// Built from [`StructuralElementSpecs`] with [`StructuralElements::new`]. A
357/// parsing state carries the set in its extension
358/// ([`FlmStateExt::structural`](crate::lang::FlmStateExt::structural)); a
359/// registry's set is available as
360/// [`BuiltLang::structural`](crate::lang::BuiltLang::structural).
361#[derive(Debug)]
362pub struct StructuralElements {
363 /// See [`StructuralElementSpecs::text`].
364 pub text: Arc<ElementSpec>,
365 /// See [`StructuralElementSpecs::comment`].
366 pub comment: Arc<ElementSpec>,
367 /// See [`StructuralElementSpecs::container`].
368 pub container: Arc<ElementSpec>,
369 /// See [`StructuralElementSpecs::group`].
370 pub group: Arc<ElementSpec>,
371 /// See [`StructuralElementSpecs::math`].
372 pub math: Arc<ElementSpec>,
373 /// See [`StructuralElementSpecs::verbatim`].
374 pub verbatim: Arc<ElementSpec>,
375 /// See [`StructuralElementSpecs::opaque_wrapper`].
376 pub opaque_wrapper: Arc<ElementSpec>,
377 /// See [`StructuralElementSpecs::paragraph`].
378 pub paragraph: Arc<ElementSpec>,
379 /// See [`StructuralElementSpecs::parbreak`].
380 pub parbreak: Arc<ElementSpec>,
381 /// See [`StructuralElementSpecs::placeholder`].
382 pub placeholder: Arc<ElementSpec>,
383 /// See [`StructuralElementSpecs::field`].
384 pub field: Arc<ElementSpec>,
385 /// See [`StructuralElementSpecs::unknown_macro`].
386 pub unknown_macro: Arc<ElementSpec>,
387 /// See [`StructuralElementSpecs::unknown_environment`].
388 pub unknown_environment: Arc<ElementSpec>,
389}
390
391impl StructuralElements {
392 /// Freezes `specs` into shared element values. Aspects can no longer be
393 /// attached afterwards.
394 pub fn new(specs: StructuralElementSpecs) -> StructuralElements {
395 StructuralElements {
396 text: Arc::new(specs.text),
397 comment: Arc::new(specs.comment),
398 container: Arc::new(specs.container),
399 group: Arc::new(specs.group),
400 math: Arc::new(specs.math),
401 verbatim: Arc::new(specs.verbatim),
402 opaque_wrapper: Arc::new(specs.opaque_wrapper),
403 paragraph: Arc::new(specs.paragraph),
404 parbreak: Arc::new(specs.parbreak),
405 placeholder: Arc::new(specs.placeholder),
406 field: Arc::new(specs.field),
407 unknown_macro: Arc::new(specs.unknown_macro),
408 unknown_environment: Arc::new(specs.unknown_environment),
409 }
410 }
411
412 /// Returns every structural element, in the same fixed order as [`NAMES`].
413 pub fn all(&self) -> [&Arc<ElementSpec>; 13] {
414 [
415 &self.text,
416 &self.comment,
417 &self.container,
418 &self.group,
419 &self.math,
420 &self.verbatim,
421 &self.opaque_wrapper,
422 &self.paragraph,
423 &self.parbreak,
424 &self.placeholder,
425 &self.field,
426 &self.unknown_macro,
427 &self.unknown_environment,
428 ]
429 }
430
431 /// Returns the structural element named `name`, when `name` is one of
432 /// [`NAMES`]; `None` otherwise.
433 pub fn by_name(&self, name: &str) -> Option<&Arc<ElementSpec>> {
434 self.all().into_iter().find(|element| element.name == name)
435 }
436}
437
438impl Default for StructuralElements {
439 fn default() -> StructuralElements {
440 StructuralElements::new(StructuralElementSpecs::default())
441 }
442}
443
444#[cfg(test)]
445mod tests {
446 use super::*;
447 use crate::model::aspects::BlockRoleAspect;
448
449 #[test]
450 fn the_default_set_names_every_shape_in_order() {
451 let set = StructuralElements::default();
452 let names: Vec<&str> = set.all().iter().map(|element| element.name.as_str()).collect();
453 assert_eq!(names, NAMES);
454 assert!(set.by_name(PARBREAK).is_some());
455 assert!(set.by_name("flm.nope").is_none());
456 }
457
458 #[test]
459 fn the_paragraph_is_a_block_and_the_marker_carries_no_role() {
460 let set = StructuralElements::default();
461 assert!(set.paragraph.has_aspect::<dyn BlockRoleAspect>());
462 assert!(set.text.has_aspect::<dyn BlockRoleAspect>());
463 assert!(!set.parbreak.has_aspect::<dyn BlockRoleAspect>());
464 }
465
466 #[test]
467 fn display_mathematics_is_a_displayed_item_and_inline_mathematics_inline_content() {
468 use crate::lang::{FlmSource, LangInputs, ParseOptions, build_language, parse_fragment};
469 use crate::model::aspects::block_role_of;
470 use crate::model::doc::FragmentLayout;
471
472 let mut inputs = LangInputs::new();
473 inputs.parsing.dollar_math = true;
474 let lang = build_language(inputs);
475 let source = Arc::new(FlmSource::new(r"\(a\) $b$ \[c\] $$d$$"));
476 let fragment = parse_fragment(&lang, source, FragmentLayout::Inline, &ParseOptions::default())
477 .expect("a parse");
478 let roles: Vec<BlockRole> = fragment
479 .tree()
480 .root()
481 .descendants()
482 .filter(|node| node.ext().element.name.as_str() == MATH)
483 .map(|node| block_role_of(&node))
484 .collect();
485 assert_eq!(roles, [BlockRole::DEFAULT, BlockRole::DEFAULT, BlockRole::Displayed, BlockRole::Displayed]);
486 }
487}