Skip to main content

flm_core/stdlib/features/blocks/
mod.rs

1//! The `blocks` feature lays out every document tree in paragraphs and blocks
2//! and resolves its text, in a rewrite stage that a plan includes when its
3//! capability is demanded or required, and it checks the tree contract.
4//!
5//! # What the feature provides to an author
6//!
7//! An author separates paragraphs with a blank line, and a block-level
8//! construct (a list, a quotation, a float) is placed between paragraphs,
9//! never inside one; a displayed formula stands inside the paragraph it is
10//! written in. The typographic spellings of TeX are shown as
11//! the characters they stand for: `--` as an en dash, ``` `` ``` and `''` as
12//! curly quotes, `...` as an ellipsis, each family switched on or off by the
13//! feature's configuration ([`BlocksConfig`]). The language guide describes
14//! these rules for authors: [paragraphs, blocks and
15//! typography](crate::guide::language_syntax#paragraphs-blocks-and-typography).
16//!
17//! The work is done by the block-structure pass
18//! ([`crate::lang::rewrites::blocks`]), a plain function over a tree: it lays
19//! out each content region (a run of sibling nodes laid out together) as
20//! blocks, as inline content or unchanged, from the block role of each
21//! element and the layout each element declares for its arguments and body,
22//! and it resolves the text once (merged text nodes, collapsed whitespace, the
23//! typographic substitutions). This feature makes that pass a part of the
24//! pipeline.
25//!
26//! # What the feature provides to the pipeline
27//!
28//! A *capability* ([`CapabilityDef`]) is a registered dotted name for a state
29//! of processing that a stage brings about; a stage declares the capabilities
30//! it provides and requires, and a caller demands the capabilities it wants
31//! ([stages, capabilities and
32//! plans](crate::guide::concepts_overview#stages-capabilities-and-plans)). The
33//! feature registers:
34//!
35//! - [`BLOCKS`] (`flm.blocks`), the parent capability: a decision about block
36//!   structure has been made. Two capabilities *refine* it
37//!   ([refinement](crate::guide::pipeline#refinement)): each is one way of
38//!   satisfying it, and a plan that demands both is refused.
39//! - [`STRUCTURE`] (`flm.blocks.structure`), the rewrite stage
40//!   ([`RewriteStage`]: a stage that turns one tree into another before the
41//!   trees are frozen) that runs the block-structure pass over each tree, with
42//!   the region layout of the tree's top level
43//!   ([`FragmentLayout`](crate::model::doc::FragmentLayout)) and the feature's
44//!   configuration. It publishes
45//!   the trees it produces in the trees table [`STRUCTURED`]
46//!   (`flm.blocks.structured`; a [`TreesTable`], the table in which a rewrite
47//!   stage publishes the trees it produces), which is also the capability it
48//!   provides, the refinement of `flm.blocks` marked as the default: a plan
49//!   that demands `flm.blocks` alone gets structured trees.
50//!   A lowering rule that reads paragraphs requires `flm.blocks.structured`
51//!   (the rule for paragraphs, for example), which puts the stage into a
52//!   rendering plan.
53//! - [`RAW`] (`flm.blocks.raw`), a marker stage that does nothing and provides
54//!   the capability of the same name, the other refinement of `flm.blocks`:
55//!   the trees stay as parsed, without paragraphs and with the text unresolved.
56//!   The lowering rules of the `latex-recomposed` backend require it, because
57//!   that backend writes the document back as LaTeX source.
58//! - [`CONTRACT_CHECK`] (`flm.blocks.check-contract`, in the module [`check`]),
59//!   the check stage that runs the [tree-contract
60//!   checker](crate::lang::rewrites::blocks::check) over every [frozen
61//!   tree](crate::guide::concepts_overview#frozen-trees-and-computed-data) and
62//!   provides [`CONTRACT_CHECKED`] (`flm.blocks.contract-checked`), a member of
63//!   the collection [`flm.validated`](crate::stdlib::VALIDATED) that every
64//!   standard workflow demands.
65//! - The settings declaration of [`BlocksConfig`], whose fields are the
66//!   feature's settings keys ([`crate::core::settings`]).
67//!
68//! # Configuration
69//!
70//! [`BlocksConfig`] says which families of typographic substitution apply. It
71//! is the feature's configuration, the plain Rust value the feature is
72//! constructed from ([`Blocks::new`]); it is fixed when the registry is built
73//! and cannot vary per document or per render ([settings, options and
74//! configuration](crate::guide::concepts_overview#settings-options-and-configuration)).
75//! The feature also gives the four flags of [`BlocksConfig`] as an input of
76//! the [registry digest](crate::model::digest)
77//! ([`FeatureBuilder::digest_input`]), a number computed from everything about
78//! a registry that can change what processing produces: the trees a run
79//! freezes depend on these flags, so two registries that differ in them must
80//! not share cached trees.
81//!
82//! # Interaction with user definitions
83//!
84//! A use site of a [user
85//! definition](crate::lang::rewrites::userdefs::Definition) (a place where a
86//! document uses a macro, environment or special character sequence that is
87//! defined by substitution; see [`crate::lang::rewrites::userdefs`]) that is
88//! not yet expanded can hide a paragraph break that the definition's template
89//! holds, so the structure stage must not run before the plan has decided
90//! what happens to user definitions. Whenever the registry declares the
91//! capability [`USERDEFS`] (`flm.userdefs`, from the
92//! [`userdefs`](crate::stdlib::features::userdefs) feature), the structure
93//! stage therefore requires it and is ordered after it. Either alternative of
94//! that capability satisfies the requirement: the use sites expanded in the
95//! tree (`flm.userdefs.expanded`), or kept in the tree for the lowering rules
96//! (`flm.userdefs.kept`). Under the same condition, the stage is also ordered
97//! after [`ALWAYS_EXPANDED`] (`flm.userdefs.always-expanded`), so that the
98//! rewrite stage `flm.userdefs.expand-always` runs before the structure stage
99//! whenever both are in the plan. An ordering never adds a stage to a
100//! plan: a stage runs because something requires a capability it provides,
101//! never because another stage is ordered after it. With no `userdefs` feature
102//! registered there are no user definitions, and the structure stage has no
103//! requirement.
104//!
105//! # When the pass fails
106//!
107//! When the block-structure pass fails over a tree, the stage returns a
108//! [`RewriteError`] carrying one Error diagnostic, and the tree is absent from
109//! every later table and from the frozen trees. Content nested more deeply than
110//! the [recursion guard](crate::lang::guard) allows
111//! (`flm.blocks.nesting-too-deep`) gives [`RewriteError::NestingTooDeep`];
112//! when the failure happens inside a [synthesized
113//! value](crate::guide::concepts_overview#synthesized-values), value catch-up
114//! reports it again under a condition of its own
115//! ([`StageCx::resolve_value`]).
116//! Every other failure gives [`RewriteError::Failed`].
117//!
118//! # Items
119//!
120//! - [`Blocks`], the feature, constructed with [`Blocks::new`] from a
121//!   [`BlocksConfig`] (re-exported here from the block-structure pass).
122//! - [`FEATURE`], the feature's name; [`BLOCKS`], [`STRUCTURE`],
123//!   [`STRUCTURED`] and [`RAW`], the names of its capabilities, stages and
124//!   trees table.
125//! - [`check`]: the contract check stage, with [`CONTRACT_CHECK`] and
126//!   [`CONTRACT_CHECKED`].
127
128pub mod check;
129
130use std::sync::Arc;
131
132use techy::core::node::NodeTree;
133
134use crate::model::addr::TreeId;
135use crate::core::settings::SettingsDecl;
136use crate::core::plan::PlanCx;
137use crate::core::registry::{BuildError, CapabilityDef, FeatureBuilder, FeatureInfo, FlmFeature};
138use crate::core::run::{RewriteCx, StageCx};
139use crate::core::stage::{
140    Effect, Needs, RewriteDecl, RewriteError, RewriteStage, Scope, Stage, StageDecl, TreesTable,
141};
142use crate::core::data::store::StageOut;
143use crate::core::data::table::TableName;
144use crate::lang::rewrites::blocks::{StructureError, structure_with_guard};
145use crate::lang::{Flm, FlmDiagnostics};
146use crate::stdlib::VALIDATED;
147use crate::stdlib::features::userdefs::{ALWAYS_EXPANDED, USERDEFS};
148
149use self::check::ContractCheck;
150
151pub use self::check::{CONTRACT_CHECK, CONTRACT_CHECKED};
152pub use crate::lang::rewrites::blocks::BlocksConfig;
153
154/// The feature's registered name, `blocks`. It is also the middle segment of
155/// the names of the feature's stages and diagnostics (`flm.blocks.structure`,
156/// `flm.blocks.nesting-too-deep`).
157pub const FEATURE: &str = "blocks";
158
159/// The parent capability `flm.blocks`: a decision about block structure has
160/// been made. Two capabilities refine it, [`STRUCTURED`] (the default) and
161/// [`RAW`]; a plan that demands both is refused. See the module documentation.
162pub const BLOCKS: &str = "flm.blocks";
163
164/// The name of the rewrite stage that runs the block-structure pass over each
165/// tree, `flm.blocks.structure`. The stage provides [`STRUCTURED`].
166pub const STRUCTURE: &str = "flm.blocks.structure";
167
168/// The trees table `flm.blocks.structured`, in which the [`STRUCTURE`] stage
169/// publishes the trees it produces. A rewrite stage's trees table has the name
170/// of the capability the stage provides, so `flm.blocks.structured` is also
171/// that capability: the refinement of [`BLOCKS`] marked as the default, so
172/// that a plan that demands `flm.blocks` alone gets structured trees.
173///
174/// A stage that declares an optional read of this table learns whether the
175/// plan structured the trees: the table is written exactly where the
176/// structure stage ran.
177pub const STRUCTURED: TableName<TreesTable> = TableName::new("flm.blocks.structured");
178
179/// The name of the marker stage `flm.blocks.raw` and of the capability it
180/// provides: the refinement of [`BLOCKS`] under which the trees stay as
181/// parsed, without paragraphs and with the text unresolved. The marker stage
182/// does nothing; it exists so that a plan can choose this alternative, which
183/// excludes the [`STRUCTURE`] stage. The lowering rules of the
184/// `latex-recomposed` backend require it.
185pub const RAW: &str = "flm.blocks.raw";
186
187/// The declaration of the feature's settings: its configuration,
188/// [`BlocksConfig`], whose fields are the settings keys
189/// ([`crate::core::settings`]).
190fn settings() -> SettingsDecl {
191    SettingsDecl::new(FEATURE).config::<BlocksConfig>(
192        "Which families of typographic substitution apply when the text of a document is \
193         resolved (curly quotes, dashes, ellipses). Fixed when the registry is built: it \
194         cannot vary per document or per render.",
195    )
196}
197
198/// The `blocks` feature ([`FlmFeature`]): it registers the block-structure
199/// rewrite stage, the raw marker stage, the contract check stage, their
200/// capabilities and the feature's settings. See the module documentation.
201///
202/// Construct it with [`Blocks::new`] from a [`BlocksConfig`], or with
203/// [`Blocks::default`] for every typographic substitution on. The standard
204/// package registers it from the `blocks` field of
205/// [`StdlibConfig`](crate::stdlib::StdlibConfig).
206#[derive(Debug, Clone)]
207pub struct Blocks {
208    config: BlocksConfig,
209}
210
211impl Blocks {
212    /// Returns the feature with the configuration `config`, which stays fixed
213    /// for the life of every registry the feature is built into.
214    pub fn new(config: BlocksConfig) -> Blocks {
215        Blocks { config }
216    }
217
218    /// Returns the configuration the feature was constructed with.
219    pub fn config(&self) -> &BlocksConfig {
220        &self.config
221    }
222}
223
224impl Default for Blocks {
225    /// Returns the feature with the default configuration
226    /// ([`BlocksConfig::default`]): every family of typographic substitution
227    /// on.
228    fn default() -> Blocks {
229        Blocks::new(BlocksConfig::default())
230    }
231}
232
233impl FlmFeature for Blocks {
234    fn info(&self) -> FeatureInfo {
235        FeatureInfo::new(FEATURE, "Block structure").docs(
236            "Lays out every document tree in paragraphs and blocks, from the block role of \
237             each element and the layout it declares for its arguments and body, and resolves \
238             the text once: the `flm.blocks.structure` rewrite stage provides \
239             `flm.blocks.structured`; the `flm.blocks.raw` marker stage keeps the trees as \
240             parsed; the `flm.blocks.check-contract` stage checks the tree contract.",
241        )
242    }
243
244    fn settings(&self) -> Option<SettingsDecl> {
245        Some(settings())
246    }
247
248    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
249        b.capability(CapabilityDef::new(BLOCKS).docs(
250            "A decision about block structure has been made: the trees are laid out in \
251             paragraphs and blocks (`flm.blocks.structured`, the default) or kept as parsed \
252             (`flm.blocks.raw`).",
253        ))?;
254        b.capability(CapabilityDef::new(RAW).refines(BLOCKS).docs(
255            "The trees are kept as parsed: no paragraphs, and the text unresolved. The \
256             alternative to `flm.blocks.structured`; a plan that demands both is refused.",
257        ))?;
258        b.rewrite_stage(Arc::new(StructureStage { config: self.config }))?;
259        b.stage(Arc::new(RawMarker))?;
260        b.capability(CapabilityDef::new(CONTRACT_CHECKED).docs(
261            "Every frozen tree satisfies the parts of the tree contract that the plan's \
262             trees are subject to, or its violations have been reported as \
263             `flm.blocks.contract-violated`. A member of `flm.validated`.",
264        ))?;
265        b.stage(Arc::new(ContractCheck))?;
266        b.collection_member(VALIDATED, CONTRACT_CHECKED)?;
267        b.digest_input(&digest_bytes(&self.config))?;
268        Ok(())
269    }
270}
271
272/// Returns the configuration as the bytes the feature gives to the registry
273/// digest: each flag as one byte, in the order the fields are declared.
274///
275/// The bytes are written out field by field rather than taken from the type's
276/// `Debug` output, because that output would change with a field rename and
277/// would change every registry digest with it.
278fn digest_bytes(config: &BlocksConfig) -> [u8; 4] {
279    [
280        u8::from(config.auto_unicode_quotes),
281        u8::from(config.ligature_unicode_quotes),
282        u8::from(config.ligature_unicode_dashes),
283        u8::from(config.ligature_unicode_ellipses),
284    ]
285}
286
287/// The rewrite stage `flm.blocks.structure`: it runs the block-structure pass
288/// over each tree, with the region layout of the tree's top level
289/// ([`FragmentLayout`](crate::model::doc::FragmentLayout)), the feature's
290/// configuration and the recursion guard's policy
291/// ([`GuardPolicy`](crate::lang::guard::GuardPolicy)) that the registry's
292/// language was built with.
293struct StructureStage {
294    config: BlocksConfig,
295}
296
297impl RewriteStage for StructureStage {
298    fn decl(&self) -> RewriteDecl {
299        RewriteDecl::new(STRUCTURE, STRUCTURED.name()).refines(BLOCKS).default().docs(
300            "Lays out each tree in paragraphs and blocks, from the block role of each element \
301             and the layout it declares for its arguments and body, and resolves the text once. \
302             Publishes the trees as `flm.blocks.structured`, the default refinement of \
303             `flm.blocks`.",
304        )
305    }
306
307    /// Requires [`USERDEFS`] and is ordered after it, whenever the registry
308    /// declares that capability; is ordered after [`ALWAYS_EXPANDED`] (an
309    /// ordering only), whenever the registry declares it. See the module
310    /// documentation, section "Interaction with user definitions".
311    fn needs(&self, cx: &PlanCx<'_>) -> Needs {
312        // A requirement and not only an ordering edge: an unexpanded definition
313        // can hide a paragraph break, so the block structure waits until the
314        // user definitions are expanded or kept, and an ordering edge alone
315        // never schedules the stage that does either.
316        let mut needs = Needs::new();
317        if cx.registry().cap_id(USERDEFS).is_some() {
318            needs = needs.requires(USERDEFS).after(USERDEFS);
319        }
320        if cx.registry().cap_id(ALWAYS_EXPANDED.name()).is_some() {
321            needs = needs.after(ALWAYS_EXPANDED.name());
322        }
323        needs
324    }
325
326    fn rewrite(
327        &self,
328        _tree_id: TreeId,
329        tree: &Arc<NodeTree<Flm>>,
330        cx: &RewriteCx<'_>,
331        diags: &mut FlmDiagnostics,
332    ) -> Result<Arc<NodeTree<Flm>>, RewriteError> {
333        let guard = cx.registry().lang().guard();
334        structure_with_guard(tree, cx.layout(), &self.config, guard, diags).map_err(|error| {
335            let diagnostic = error.diagnostic(tree);
336            match error {
337                StructureError::NestingTooDeep { .. } => RewriteError::NestingTooDeep(diagnostic),
338                _ => RewriteError::Failed(diagnostic),
339            }
340        })
341    }
342}
343
344/// The marker stage `flm.blocks.raw` ([`RAW`]): it does nothing and provides
345/// the capability of the same name, the refinement of `flm.blocks` under which
346/// the trees stay as parsed.
347struct RawMarker;
348
349impl Stage for RawMarker {
350    fn decl(&self) -> StageDecl {
351        StageDecl::new(RAW, Effect::Compute, Scope::PerTree).provides(RAW).docs(
352            "Does nothing and provides `flm.blocks.raw`, so that a plan that requires the \
353             trees as parsed excludes the `flm.blocks.structure` rewrite stage.",
354        )
355    }
356
357    fn needs(&self, _cx: &PlanCx<'_>) -> Needs {
358        Needs::new()
359    }
360
361    fn run(&self, _cx: &StageCx<'_>, _out: &mut StageOut<'_>) {}
362}
363
364#[cfg(test)]
365mod tests {
366    use super::*;
367
368    #[test]
369    fn the_digest_bytes_follow_the_flags() {
370        assert_eq!(digest_bytes(&BlocksConfig::default()), [1, 1, 1, 1]);
371        assert_eq!(digest_bytes(&BlocksConfig::no_typography()), [0, 0, 0, 0]);
372        let config = BlocksConfig { ligature_unicode_dashes: false, ..BlocksConfig::default() };
373        assert_eq!(digest_bytes(&config), [1, 1, 0, 1]);
374    }
375
376    #[test]
377    fn the_structure_stage_declares_the_default_refinement_of_blocks() {
378        let decl = StructureStage { config: BlocksConfig::default() }.decl();
379        assert_eq!(decl.name, STRUCTURE);
380        assert_eq!(decl.publishes, STRUCTURED.name());
381        assert_eq!(decl.refines.as_deref().map(|n| n.as_str()), Some(BLOCKS));
382        assert!(decl.default);
383    }
384
385    #[test]
386    fn the_raw_marker_provides_its_own_name_and_writes_nothing() {
387        let decl = RawMarker.decl();
388        assert_eq!(decl.name, RAW);
389        assert_eq!(decl.provides, [crate::model::names::CapName::from(RAW)]);
390        assert!(decl.writes.is_empty());
391    }
392}