flm_core/stdlib/backends/html/defs.rs
1//! The stylesheets and the script this backend ships, and the stage that
2//! decides how each style or script definition a document requires reaches the
3//! page.
4//!
5//! A style or script definition ([`StyleDef`], [`ScriptDef`](crate::core::registry::ScriptDef))
6//! is a stylesheet or a script that a feature's output depends on, recorded in
7//! the registry under an identifier; a lowering rule or the emitter *requires*
8//! it by identifier, and the backend that writes the output decides its
9//! *delivery*: written into the output, loaded from an address, or left to the
10//! host (see [style and script
11//! definitions](crate::guide::concepts_overview#style-and-script-definitions)).
12//! On this backend the delivery is decided here:
13//!
14//! 1. Each tree's emission and the emission of each
15//! [piece](crate::core::piece::Piece) (a document-level value placed beside
16//! the content) record the identifiers
17//! their HTML requires (`flm.output.html`, `flm.output.html.pieces`).
18//! 2. The stage [`ResolveDefinitionsStage`] collects them, adds the identifiers
19//! the host requires for the whole page (the render option
20//! [`required_definitions`](super::HtmlRenderOptions::required_definitions))
21//! and the page's own stylesheet [`STYLE_PAGE`], and looks each identifier up
22//! among the registry's style and script definitions.
23//! 3. For each one, the delivery is the definition's declared content, unless
24//! the render option [`definitions`](super::HtmlRenderOptions::definitions)
25//! gives another ([`DefinitionOverride`]). A part of the declared content
26//! supplied by a table ([`DefContent::Table`]) is replaced by the text that
27//! table holds for the document, as an [`Inline`](DefContent::Inline) part.
28//! 4. The stage writes the result into one table, [`DEFINITIONS_TABLE`]
29//! (`flm.html.definitions`): every definition the document requires, once
30//! each, with its kind, the feature that declared it and its delivery.
31//!
32//! The regions stage reads that table, and nothing else, to write the page's
33//! stylesheets and scripts ([`super::page`]). A host that assembles a page of
34//! its own reads the same table, and a bundler reads its serialized form
35//! ([`Table::project`]).
36//!
37//! # What this backend ships
38//!
39//! Seven stylesheets, one per concern, so that a page carries only what its
40//! content needs (a document with no mathematics loads no rules for
41//! mathematics):
42//!
43//! | identifier | what it styles |
44//! |---|---|
45//! | `flm.html.style.core` | paragraphs, blocks, spans, links, images, decorations |
46//! | `flm.html.style.headings` | the six heading sizes |
47//! | `flm.html.style.verbatim` | content set character for character |
48//! | `flm.html.style.math-passthrough` | a displayed formula, and content written inside a formula |
49//! | `flm.html.style.lists` | lists and their labels; a run of lines |
50//! | `flm.html.style.errors` | what the page shows where something could not be produced |
51//! | `flm.html.style.page` | the page's own typography and the width of its content |
52//!
53//! Which element requires which stylesheet is stated by the [conventions
54//! table](super::conventions). No element requires `flm.html.style.page`: the
55//! resolve stage adds it, because the page this backend assembles needs it. A
56//! host that builds a page of its own around the HTML of each tree can leave
57//! that row out.
58//!
59//! **The first line of every text this backend ships is a comment holding the
60//! identifier of the definition it belongs to**: the line
61//! `/* flm.html.style.core */`, the line `/* flm.html.mathjax */`, before any
62//! other comment and before the first rule. A page written by this backend
63//! also records that identifier as an attribute of the `<style>` or `<script>`
64//! element holding the text ([`DEF_ATTRIBUTE`](super::page::DEF_ATTRIBUTE)),
65//! but a text passed on by itself carries no attribute. The comment lets a
66//! reader that sees only the text (a tool that reads a finished page back, a
67//! host's build step, a person reading the bytes) tell which definition it
68//! has, and in particular tell `flm.html.style.page`, whose selectors are not
69//! all classes of the [HTML contract](super::CONVENTIONS), from the others.
70//!
71//! Each stylesheet is one `@layer flm { … }` block. A **cascade layer** is a
72//! named group of CSS rules; a rule outside every layer wins over a rule inside
73//! one, regardless of their selectors. A host therefore restyles this backend's
74//! output with ordinary rules and never needs a more specific selector than the
75//! shipped one. Inside the layer, each stylesheet declares on
76//! `:root` the custom properties (`--flm-…`) it uses; a host that only wants a
77//! different value sets that property instead of replacing a rule. Every
78//! selector begins with a class of the HTML contract, so embedding the output
79//! in a host's page restyles nothing of the host's; `flm.html.style.page` is
80//! the only exception, and says so in its own text.
81//!
82//! One script, `flm.html.mathjax` ([`mathjax_script`]): the formula renderer,
83//! in two parts, its configuration and then the address its program is loaded
84//! from. It is declared in [its own module](super::mathjax), which also says
85//! what a host that does not trust the authors of the mathematics it renders
86//! must configure for itself.
87//!
88//! # Conditions
89//!
90//! The resolve stage reports [`UnknownRequirement`] for a required identifier
91//! that no feature declares, [`UnknownDefinition`] for an entry of the
92//! `definitions` option that no feature declares, and [`DefinitionPartMissing`]
93//! for a part supplied by a table that holds no text. The regions stage reports
94//! [`DefinitionNotInlinable`] for a part of a definition it cannot write into
95//! the page.
96
97use std::collections::{BTreeMap, BTreeSet};
98use std::sync::Arc;
99
100use techy::error::{Diagnostic, DiagnosticInfo, DiagnosticValue, ToDiagnosticValue};
101use techy::serialize::SerialValue;
102
103use crate::core::data::store::StageOut;
104use crate::core::data::table::{
105 PieceClass, ProjectCx, SingletonTable, Table, TableHandle, TableName,
106};
107use crate::core::plan::PlanCx;
108use crate::core::registry::{
109 BuildError, DefContent, DefinitionText, FeatureBuilder, FlmRegistry, StyleDef,
110};
111use crate::core::run::StageCx;
112use crate::core::stage::{Effect, Needs, Scope, Stage, StageDecl};
113use crate::lang::{FlmOrigin, nowhere};
114use crate::model::names::{CapName, FeatureName, Name};
115
116use super::conventions::{
117 STYLE_CORE, STYLE_ERRORS, STYLE_HEADINGS, STYLE_LISTS, STYLE_MATH_PASSTHROUGH, STYLE_VERBATIM,
118};
119use super::emit::NOWHERE_LABEL;
120use super::feature::{DefinitionOverride, HtmlRenderOptions};
121use super::mathjax::mathjax_script;
122use super::stages::{OUTPUT_TABLE, PIECES_TABLE, stage_failed};
123
124/// The name of the stage that resolves the definitions,
125/// `flm.html.resolve-definitions` ([`ResolveDefinitionsStage`]).
126pub const RESOLVE_STAGE: &str = "flm.html.resolve-definitions";
127
128/// The typed name of the definitions table, `flm.html.definitions`: every
129/// style and script definition the document requires, each with its delivery
130/// ([`ResolvedDefinitions`]).
131pub const DEFINITIONS_TABLE: TableName<ResolvedDefinitions> =
132 TableName::new("flm.html.definitions");
133
134/// The style definition of the page's own typography and the width of its
135/// content, `flm.html.style.page`.
136///
137/// No element requires it: it styles the page this backend assembles, and the
138/// resolve stage ([`ResolveDefinitionsStage`]) adds it to what the document's
139/// content required. It is the only stylesheet whose selectors are not all
140/// classes of the [HTML contract](super::CONVENTIONS), because a page has a
141/// `body` and a document does not.
142pub const STYLE_PAGE: &str = "flm.html.style.page";
143
144// --- what this backend ships ------------------------------------------------------------
145
146/// The seven stylesheets this backend ships: the identifier, the text, and the
147/// description recorded with the definition.
148///
149/// The order is the order in which they are registered, which is the order in
150/// which the definitions table lists them and a page writes them.
151const STYLESHEETS: [(&str, &str, &str); 7] = [
152 (
153 STYLE_CORE,
154 include_str!("css/core.css"),
155 "paragraphs, blocks, the display styles of a span, links, images and the three \
156 decorations",
157 ),
158 (STYLE_HEADINGS, include_str!("css/headings.css"), "the six heading sizes"),
159 (
160 STYLE_VERBATIM,
161 include_str!("css/verbatim.css"),
162 "content set character for character, inline and as a block",
163 ),
164 (
165 STYLE_MATH_PASSTHROUGH,
166 include_str!("css/math-passthrough.css"),
167 "a displayed formula, and content written inside a formula",
168 ),
169 (
170 STYLE_LISTS,
171 include_str!("css/lists.css"),
172 "lists with their entries and labels, and a run of lines with its alignment",
173 ),
174 (
175 STYLE_ERRORS,
176 include_str!("css/errors.css"),
177 "what the page shows where the document asked for something that could not be \
178 produced",
179 ),
180 (
181 STYLE_PAGE,
182 include_str!("css/page.css"),
183 "the page's own typography and the width the content is held to; required by the \
184 page this backend assembles and by no element",
185 ),
186];
187
188/// Returns the seven style definitions this backend ships, in the order in
189/// which they are registered, which is the order in which the definitions table
190/// lists them and a page writes them.
191///
192/// The content of each is one part, its text ([`DefContent::Inline`]). The
193/// [module documentation](self#what-this-backend-ships) lists them and the
194/// rules their texts follow.
195pub fn stylesheets() -> Vec<StyleDef> {
196 STYLESHEETS
197 .iter()
198 .map(|(id, text, docs)| StyleDef {
199 id: Name::from(*id),
200 content: vec![DefContent::Inline(String::from(*text))],
201 docs: String::from(*docs),
202 })
203 .collect()
204}
205
206/// Registers this backend's seven style definitions, the formula renderer's
207/// script definition, the definitions table and the resolve stage. The `html`
208/// feature ([`super::HtmlBackend`]) calls it from its own registration.
209///
210/// # Errors
211///
212/// Never fails: the feature builder accepts each of these registrations, and a
213/// name clash is reported when the registry is built. The `Result` lets the
214/// `html` feature's registration call this function with `?`.
215pub fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
216 for style in stylesheets() {
217 b.style_def(style)?;
218 }
219 b.script_def(mathjax_script())?;
220 b.table(
221 DEFINITIONS_TABLE,
222 "the stylesheets and scripts the page requires, each with how it is delivered",
223 )?;
224 b.stage(Arc::new(ResolveDefinitionsStage))?;
225 Ok(())
226}
227
228// --- the table --------------------------------------------------------------------------
229
230/// Whether a row of [`ResolvedDefinitions`] is a stylesheet or a script.
231///
232/// The kind decides where the page writes the definition: a stylesheet in the
233/// head, a script at the end of the body.
234#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
235pub enum DefinitionKind {
236 /// A stylesheet.
237 Style,
238 /// A script.
239 Script,
240}
241
242impl DefinitionKind {
243 /// Returns the kind's stable name, `style` or `script`, as the table's
244 /// projection writes it.
245 pub fn as_str(self) -> &'static str {
246 match self {
247 DefinitionKind::Style => "style",
248 DefinitionKind::Script => "script",
249 }
250 }
251}
252
253/// One row of the definitions table: a style or script definition the document
254/// requires, with the delivery it ended up with.
255#[derive(Debug, Clone, PartialEq, Eq)]
256pub struct ResolvedDefinition {
257 /// The definition's identifier, as the requirement gave it.
258 pub id: Name,
259 /// Whether it is a stylesheet or a script.
260 pub kind: DefinitionKind,
261 /// The feature that declared it.
262 pub owner: FeatureName,
263 /// How it reaches the page: the parts written for it, in order, or the
264 /// statement that the host's own page or bundle supplies it and the page
265 /// writes nothing. This is the declared content unless the render option
266 /// [`definitions`](super::HtmlRenderOptions::definitions) put something
267 /// else in its place.
268 pub delivery: DefinitionOverride,
269}
270
271/// The definitions table, `flm.html.definitions` ([`DEFINITIONS_TABLE`]):
272/// every style and script definition the document requires, once each, with
273/// its delivery.
274///
275/// A requirement is only an identifier; this table records, for each
276/// identifier, how the definition reaches the page. The regions stage reads it
277/// and reads nothing else about definitions. A host that assembles its own page
278/// around the per-tree HTML of `flm.output.html` reads it too, including the
279/// rows whose delivery is [`ProvidedByHost`](DefinitionOverride::ProvidedByHost),
280/// so that it knows what the document needs; a bundler works from its
281/// serialized form ([`Table::project`]). The stage [`ResolveDefinitionsStage`]
282/// writes it once per document.
283#[derive(Debug, Clone, Default, PartialEq, Eq)]
284pub struct ResolvedDefinitions {
285 /// The rows: the stylesheets first, in the order in which the features
286 /// registered them, then the scripts in the same way.
287 pub definitions: Vec<ResolvedDefinition>,
288}
289
290impl ResolvedDefinitions {
291 /// Returns the row of the definition `id`, or `None` when the document
292 /// does not require it.
293 pub fn get(&self, id: &str) -> Option<&ResolvedDefinition> {
294 self.definitions.iter().find(|definition| definition.id.as_str() == id)
295 }
296
297 /// Returns the rows of one kind, in order: what the page writes in the
298 /// head (stylesheets) or at the end of the body (scripts).
299 pub fn of_kind(&self, kind: DefinitionKind) -> impl Iterator<Item = &ResolvedDefinition> {
300 self.definitions.iter().filter(move |definition| definition.kind == kind)
301 }
302}
303
304impl Table for ResolvedDefinitions {
305 /// The stage writes the table once, for the whole document, so a
306 /// non-empty table piece replaces what the table held.
307 fn absorb(&mut self, piece: ResolvedDefinitions) {
308 if !piece.definitions.is_empty() {
309 self.definitions = piece.definitions;
310 }
311 }
312
313 /// One entry per row: `{id, kind, owner, provided_by_host, parts}`, each
314 /// part one of `{inline}`, `{file}`, `{url}` or `{table}`. A bundler or a site
315 /// generator works from this list.
316 fn project(&self, _cx: &dyn ProjectCx) -> SerialValue {
317 SerialValue::List(
318 self.definitions
319 .iter()
320 .map(|definition| {
321 let (provided, parts) = match &definition.delivery {
322 DefinitionOverride::ProvidedByHost => (true, Vec::new()),
323 DefinitionOverride::Parts(parts) => (false, parts.clone()),
324 };
325 SerialValue::Map(vec![
326 (String::from("id"), SerialValue::Str(definition.id.to_string())),
327 (
328 String::from("kind"),
329 SerialValue::Str(String::from(definition.kind.as_str())),
330 ),
331 (String::from("owner"), SerialValue::Str(definition.owner.to_string())),
332 (String::from("provided_by_host"), SerialValue::Bool(provided)),
333 (
334 String::from("parts"),
335 SerialValue::List(parts.iter().map(project_part).collect()),
336 ),
337 ])
338 })
339 .collect(),
340 )
341 }
342
343 fn piece_class(&self) -> PieceClass {
344 if self.definitions.is_empty() { PieceClass::Empty } else { PieceClass::DocumentFact }
345 }
346}
347
348impl SingletonTable for ResolvedDefinitions {
349 const NAME: &'static str = "flm.html.definitions";
350}
351
352/// One part of a delivery, projected: `{inline}`, `{file}`, `{url}` or
353/// `{table}`. The stage puts a table's text in the place of a `table` part, so
354/// a row it wrote holds none; a table built by other means may.
355fn project_part(part: &DefContent) -> SerialValue {
356 let (key, value) = match part {
357 DefContent::Inline(text) => ("inline", text.clone()),
358 DefContent::File(path) => ("file", path.clone()),
359 DefContent::Url(address) => ("url", address.clone()),
360 DefContent::Table(table) => ("table", table.to_string()),
361 };
362 SerialValue::Map(vec![(String::from(key), SerialValue::Str(value))])
363}
364
365// --- conditions -------------------------------------------------------------------------
366
367/// Condition `flm.html.unknown-requirement` (Error): an identifier that a
368/// lowering rule or the emitter required, or that the render option
369/// [`required_definitions`](super::HtmlRenderOptions::required_definitions)
370/// lists, is not the identifier of any style or script definition in the
371/// registry.
372///
373/// It reports a mistake in a feature, in the host's render option
374/// `required_definitions`, or in the way the registry was assembled, and never
375/// anything a document can write. Reported by
376/// [`ResolveDefinitionsStage`], at no position in a document. Recovery: the
377/// requirement is dropped (nothing is written for it, and it is left out of the
378/// definitions table) and the rest of the page is produced as usual.
379#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
380#[diagnostic(
381 id = "flm.html.unknown-requirement",
382 message = "the HTML page requires the stylesheet or script `{definition}` (for the document's \
383 content, for the page itself, or through the render option \
384 `required_definitions`), but no registered feature declares a stylesheet or \
385 script with that identifier"
386)]
387pub struct UnknownRequirement {
388 /// The identifier that was required.
389 pub definition: String,
390}
391
392/// Condition `flm.html.unknown-definition` (Warning): an entry of the render
393/// option [`definitions`](super::HtmlRenderOptions::definitions) has an
394/// identifier that is not the identifier of any style or script definition in
395/// the registry.
396///
397/// Reported by [`ResolveDefinitionsStage`], at no position in a document.
398/// Recovery: that entry of the option is ignored. It is a Warning rather than
399/// an Error because nothing about the page changes: the likely cause is a
400/// misspelled identifier, or a host carrying settings for a feature the
401/// registry does not hold.
402#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
403#[diagnostic(
404 id = "flm.html.unknown-definition",
405 message = "the render option `definitions` lists `{definition}`, but no registered feature \
406 declares a stylesheet or script with that identifier"
407)]
408pub struct UnknownDefinition {
409 /// The identifier the option listed.
410 pub definition: String,
411}
412
413/// Condition `flm.html.definition-part-missing` (Error): a part of a style or
414/// script definition the document requires is supplied by a table
415/// ([`DefContent::Table`]), and the run holds no text for it: the table is
416/// absent (no stage of the plan wrote it) or holds an empty text.
417///
418/// It reports a mistake in the feature that declares the definition (its stage
419/// did not run or wrote nothing), never anything a document can write.
420/// Reported by [`ResolveDefinitionsStage`], at no position in a document.
421/// Recovery: the part is empty; the definition's other parts, and the rest of
422/// the page, are written as usual.
423#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
424#[diagnostic(
425 id = "flm.html.definition-part-missing",
426 message = "the {kind} `{definition}` takes a part from the table `{table}`, but {condition}"
427)]
428pub struct DefinitionPartMissing {
429 /// What the definition is, `stylesheet` or `script`.
430 pub kind: String,
431 /// The definition's identifier.
432 pub definition: String,
433 /// The table the part names.
434 pub table: String,
435 /// What the run found: `no stage wrote that table` where the table is
436 /// absent, or ``the table `<name>` holds no text`` where it holds an
437 /// empty text.
438 pub condition: String,
439}
440
441/// The part of a style or script definition that could not be written into the
442/// page, and why: the reason carried by [`DefinitionNotInlinable`].
443///
444/// Three kinds of part cannot be written into the page: a file, a text
445/// holding the closing tag of the element it would be written into, and a part
446/// still naming the table that supplies its text.
447#[derive(Debug, Clone, PartialEq, Eq)]
448pub enum NotInlinablePart {
449 /// A part that is a **file** ([`DefContent::File`]). This library opens no
450 /// file: the host reads it and delivers its content itself, through the
451 /// render option [`definitions`](super::HtmlRenderOptions::definitions).
452 File {
453 /// The file, as the definition's part gives it.
454 path: String,
455 },
456 /// A part of **text** holding the closing tag of the element it would be
457 /// written into (`</style` or `</script`), which would end that element
458 /// early and leave the rest of the definition in the page as markup.
459 ClosingTag {
460 /// The tag of the element the text would have gone into: `style` or
461 /// `script`.
462 tag: String,
463 /// The byte offset of the closing tag in the text.
464 at: usize,
465 },
466 /// A part supplied by a **table** ([`DefContent::Table`]) that reached
467 /// the page as such: the resolve stage puts the table's text in its place,
468 /// so only a definitions table built by other means holds one.
469 Table {
470 /// The table the part names.
471 table: String,
472 },
473}
474
475impl NotInlinablePart {
476 /// Returns the stable token that identifies the case in the diagnostic's
477 /// data: `file` for [`File`](Self::File), `closing-tag` for
478 /// [`ClosingTag`](Self::ClosingTag), `table` for [`Table`](Self::Table).
479 ///
480 /// A test or a tool matches on this token rather than on the message,
481 /// whose wording is not a stable interface.
482 pub fn kind(&self) -> &'static str {
483 match self {
484 NotInlinablePart::File { .. } => "file",
485 NotInlinablePart::ClosingTag { .. } => "closing-tag",
486 NotInlinablePart::Table { .. } => "table",
487 }
488 }
489}
490
491impl std::fmt::Display for NotInlinablePart {
492 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
493 match self {
494 NotInlinablePart::File { path } => {
495 write!(
496 f,
497 "the part is the file `{path}`, and this library does not read files; in the \
498 render option `definitions`, give the file's content as text, or an address \
499 the page loads, or mark the stylesheet or script as provided by the host's \
500 own page"
501 )
502 }
503 NotInlinablePart::ClosingTag { tag, at } => write!(
504 f,
505 "the part's text contains the closing tag `</{tag}` (in any letter case) at byte \
506 {at}, which would end the `<{tag}>` element it is written into"
507 ),
508 NotInlinablePart::Table { table } => write!(
509 f,
510 "the part must be the text of the table `{table}`, and only the stage that \
511 resolves the page's stylesheets and scripts reads that table"
512 ),
513 }
514 }
515}
516
517/// Diagnostic data: a map holding the [`kind`](NotInlinablePart::kind) token
518/// and that case's own facts (`path`, or `tag` and `at`), never the message
519/// text, so that a test or a tool reading the data depends on no wording.
520impl ToDiagnosticValue for NotInlinablePart {
521 fn to_diagnostic_value(&self) -> DiagnosticValue {
522 let mut fields = vec![(String::from("kind"), self.kind().to_diagnostic_value())];
523 match self {
524 NotInlinablePart::File { path } => {
525 fields.push((String::from("path"), path.to_diagnostic_value()));
526 }
527 NotInlinablePart::ClosingTag { tag, at } => {
528 fields.push((String::from("tag"), tag.to_diagnostic_value()));
529 fields.push((String::from("at"), at.to_diagnostic_value()));
530 }
531 NotInlinablePart::Table { table } => {
532 fields.push((String::from("table"), table.to_diagnostic_value()));
533 }
534 }
535 DiagnosticValue::Map(fields)
536 }
537}
538
539/// Condition `flm.html.definition-not-inlinable` (Error): a part of a style or
540/// script definition the document requires cannot be written into the page,
541/// for the reason [`NotInlinablePart`] gives.
542///
543/// It reports a mistake in a feature's declaration or in the host's settings,
544/// never anything a document can write. Reported by the regions stage
545/// ([`HtmlRegionsStage`](super::stages::HtmlRegionsStage)), at no position in a
546/// document. Recovery: nothing is written for that part; the definition's other
547/// parts, and the rest of the page, are written as usual.
548///
549/// One condition serves both cases because the recovery is the same;
550/// [`part`](Self::part) says which case occurred and carries its facts, so that
551/// a host reads them rather than the message.
552#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
553#[diagnostic(
554 id = "flm.html.definition-not-inlinable",
555 message = "a part of the stylesheet or script `{definition}` cannot be written into the \
556 page: {part}"
557)]
558pub struct DefinitionNotInlinable {
559 /// The definition's identifier.
560 pub definition: String,
561 /// The part that could not be written, and why.
562 pub part: NotInlinablePart,
563}
564
565// --- the stage --------------------------------------------------------------------------
566
567/// The tables named by a part of a registered style or script definition
568/// ([`DefContent::Table`]), each once, in the order the definitions name them.
569fn part_tables(registry: &FlmRegistry) -> Vec<CapName> {
570 let parts = registry
571 .styles()
572 .iter()
573 .flat_map(|(_, style)| &style.content)
574 .chain(registry.scripts().iter().flat_map(|(_, script)| &script.content));
575 let mut tables: Vec<CapName> = Vec::new();
576 for part in parts {
577 if let DefContent::Table(table) = part {
578 if !tables.contains(table) {
579 tables.push(table.clone());
580 }
581 }
582 }
583 tables
584}
585
586/// One part of a definition's declared content, as the page receives it: a
587/// [`DefContent::Table`] part becomes the table's text as an
588/// [`Inline`](DefContent::Inline) part, empty with
589/// [`DefinitionPartMissing`] reported where the table is absent or holds no
590/// text, and with [`StageFailed`](super::stages::StageFailed) reported where
591/// it cannot be read; any other part is kept.
592fn resolve_part(
593 cx: &StageCx<'_>,
594 out: &mut StageOut<'_>,
595 kind: DefinitionKind,
596 definition: &str,
597 part: &DefContent,
598) -> DefContent {
599 let DefContent::Table(table) = part else { return part.clone() };
600 let found = match cx.get(TableHandle::<DefinitionText>::new(table.clone())) {
601 Ok(found) => found.map(|found| found.text.clone()),
602 Err(error) => {
603 stage_failed(out, RESOLVE_STAGE, error);
604 return DefContent::Inline(String::new());
605 }
606 };
607 let condition = match &found {
608 None => String::from("no stage wrote that table"),
609 Some(text) if text.is_empty() => format!("the table `{table}` holds no text"),
610 Some(_) => String::new(),
611 };
612 if !condition.is_empty() {
613 let kind = match kind {
614 DefinitionKind::Style => "stylesheet",
615 DefinitionKind::Script => "script",
616 };
617 out.diags.push(Diagnostic::error(
618 DefinitionPartMissing {
619 kind: String::from(kind),
620 definition: definition.to_string(),
621 table: table.to_string(),
622 condition,
623 },
624 nowhere(FlmOrigin::synthetic(NOWHERE_LABEL)),
625 ));
626 }
627 DefContent::Inline(found.unwrap_or_default())
628}
629
630/// The positions, among `registrations` (each a feature and an identifier,
631/// in registration order), of the registration that defines each identifier:
632/// of the registrations of one identifier, the one of the feature placed last
633/// in the feature order, and of one feature's, its first.
634fn chosen_registrations<'r>(
635 registry: &FlmRegistry,
636 registrations: impl Iterator<Item = (&'r FeatureName, &'r str)>,
637) -> BTreeSet<usize> {
638 let mut chosen: BTreeMap<&str, (Option<usize>, usize)> = BTreeMap::new();
639 for (index, (owner, id)) in registrations.enumerate() {
640 let position = registry.feature_position(owner);
641 match chosen.get(id) {
642 Some((best, _)) if position <= *best => {}
643 _ => {
644 chosen.insert(id, (position, index));
645 }
646 }
647 }
648 chosen.into_values().map(|(_, index)| index).collect()
649}
650
651/// The stage `flm.html.resolve-definitions` ([`RESOLVE_STAGE`]): it turns the
652/// identifiers that the document's trees and pieces required into the
653/// definitions table [`DEFINITIONS_TABLE`] (the [module documentation](self)
654/// describes the steps).
655///
656/// It runs once per document, after the HTML of the trees and of the pieces
657/// has been written and before the regions are made. The plan derives that
658/// order from the tables: this stage reads the tables the two emit stages write
659/// (`flm.output.html` and `flm.output.html.pieces`), and the regions stage
660/// reads the table this stage writes. It also reads the render options
661/// ([`HtmlRenderOptions`]).
662///
663/// When several features register one identifier, the registration of the
664/// feature placed last in the feature order is the definition (of one
665/// feature's registrations, its first), and it stands at its own place in
666/// registration order; two features that require the same stylesheet thus
667/// require it once. Style definitions are looked up before script
668/// definitions: an identifier registered as both resolves to the style
669/// definition.
670///
671/// A part supplied by a table ([`DefContent::Table`]) is replaced by the text
672/// the table holds, as an [`Inline`](DefContent::Inline) part; the stage reads
673/// every table such a part of a registered definition names, as an optional
674/// read computed over the registry when the plan is built. Conditions:
675/// [`UnknownRequirement`], [`UnknownDefinition`], [`DefinitionPartMissing`], and
676/// [`StageFailed`](super::stages::StageFailed) when a table or the options
677/// cannot be read or the table cannot be written.
678#[derive(Debug, Default, Clone, Copy)]
679pub struct ResolveDefinitionsStage;
680
681impl Stage for ResolveDefinitionsStage {
682 fn decl(&self) -> StageDecl {
683 StageDecl::new(RESOLVE_STAGE, Effect::Compute, Scope::Document)
684 .writes(DEFINITIONS_TABLE)
685 .docs(
686 "resolves the stylesheets and scripts that the document's trees and pieces \
687 required, the ones the host requires, and the host's deliveries, into \
688 `flm.html.definitions`",
689 )
690 }
691
692 /// The two tables of the emit stages and the render options, and, as
693 /// optional reads, the tables that supply a part of a registered
694 /// definition ([`DefContent::Table`]): computed over the registry when the
695 /// plan is built.
696 fn needs(&self, cx: &PlanCx<'_>) -> Needs {
697 let mut needs =
698 Needs::new().reads(OUTPUT_TABLE).reads(PIECES_TABLE).option::<HtmlRenderOptions>();
699 for table in part_tables(cx.registry()) {
700 needs = needs.reads_opt(TableHandle::<DefinitionText>::new(table));
701 }
702 needs
703 }
704
705 fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
706 let fragments = match cx.get(OUTPUT_TABLE) {
707 Ok(Some(fragments)) => fragments,
708 Ok(None) => return,
709 Err(error) => return stage_failed(out, RESOLVE_STAGE, error),
710 };
711 let pieces = match cx.get(PIECES_TABLE) {
712 Ok(pieces) => pieces,
713 Err(error) => return stage_failed(out, RESOLVE_STAGE, error),
714 };
715 let options = match cx.option::<HtmlRenderOptions>() {
716 Ok(options) => options,
717 Err(error) => return stage_failed(out, RESOLVE_STAGE, error),
718 };
719 // What the document's content and the pieces the page places
720 // required, plus the page's own stylesheet — the page is this
721 // backend's output, and nothing in a document can ask for it — and
722 // what the host requires for the page.
723 let mut required: BTreeSet<Name> = options.required_definitions.clone();
724 for fragment in fragments.trees.values() {
725 required.extend(fragment.requires.iter().cloned());
726 }
727 for piece in pieces.iter().flat_map(|pieces| &pieces.pieces) {
728 required.extend(piece.fragment.requires.iter().cloned());
729 }
730 required.insert(Name::from(STYLE_PAGE));
731
732 let registry = cx.registry();
733 // Of the registrations of one identifier, the one of the feature
734 // placed last is the definition (of one feature's, its first), at its
735 // own place: the order of the features, which the user states, decides
736 // which definition applies, and two features asking for the same
737 // stylesheet ask for it once. The two rosters are walked one after the
738 // other because the registry keeps them apart and the page writes them
739 // in two places. The choice therefore runs within a kind: where one
740 // identifier names a style definition and a script definition, the
741 // style one is the definition, whichever was registered last.
742 let mut declared: BTreeMap<&str, (DefinitionKind, &FeatureName, &Vec<DefContent>)> =
743 BTreeMap::new();
744 let mut order: Vec<&str> = Vec::new();
745 let styles = chosen_registrations(registry, registry.styles().iter().map(|(owner, style)| (owner, style.id.as_str())));
746 for (index, (owner, style)) in registry.styles().iter().enumerate() {
747 if styles.contains(&index) {
748 declared.insert(style.id.as_str(), (DefinitionKind::Style, owner, &style.content));
749 order.push(style.id.as_str());
750 }
751 }
752 let scripts = chosen_registrations(registry, registry.scripts().iter().map(|(owner, script)| (owner, script.id.as_str())));
753 for (index, (owner, script)) in registry.scripts().iter().enumerate() {
754 if scripts.contains(&index) && !declared.contains_key(script.id.as_str()) {
755 declared
756 .insert(script.id.as_str(), (DefinitionKind::Script, owner, &script.content));
757 order.push(script.id.as_str());
758 }
759 }
760
761 for id in options.definitions.keys() {
762 if !declared.contains_key(id.as_str()) {
763 out.diags.push(Diagnostic::warning(
764 UnknownDefinition { definition: id.to_string() },
765 nowhere(FlmOrigin::synthetic(NOWHERE_LABEL)),
766 ));
767 }
768 }
769 for id in &required {
770 if !declared.contains_key(id.as_str()) {
771 out.diags.push(Diagnostic::error(
772 UnknownRequirement { definition: id.to_string() },
773 nowhere(FlmOrigin::synthetic(NOWHERE_LABEL)),
774 ));
775 }
776 }
777
778 let mut resolved = ResolvedDefinitions::default();
779 for id in order {
780 if !required.contains(&Name::from(id)) {
781 continue;
782 }
783 let (kind, owner, content) = &declared[id];
784 let name = Name::from(id);
785 // An override decides the delivery and never the requirement: the
786 // row stands here whatever the host answered.
787 let delivery = match options.definitions.get(&name) {
788 Some(over) => over.clone(),
789 None => DefinitionOverride::Parts(
790 content.iter().map(|part| resolve_part(cx, out, *kind, id, part)).collect(),
791 ),
792 };
793 resolved.definitions.push(ResolvedDefinition {
794 id: name,
795 kind: *kind,
796 owner: (*owner).clone(),
797 delivery,
798 });
799 }
800 // The stylesheets first, then the scripts, each group in registration
801 // order: the two places the page writes them in.
802 resolved.definitions.sort_by_key(|definition| definition.kind);
803
804 match out.table(DEFINITIONS_TABLE) {
805 Ok(table) => *table = resolved,
806 Err(error) => stage_failed(out, RESOLVE_STAGE, error),
807 }
808 }
809}