flm_core/lang/rewrites/blocks/hook.rs
1//! The block-structure hook: the aspect by which an element lays out its own
2//! content during the layout step of the [block-structure pass](super).
3//!
4//! An aspect is a piece of behavior attached to an element when the feature
5//! registers it, and read back through a trait object (see [elements and
6//! aspects](crate::guide::concepts_overview#elements-and-aspects)). The
7//! block-structure hook, [`BlockStructure`], is the aspect for an element whose
8//! content has a block layout that its declarations cannot express. Such an
9//! element could, for example, split its body at markers and build blocks for
10//! each part, or create nodes that are never written in a document (decorators,
11//! placed at the start of its first paragraph or at the end of its last).
12//!
13//! No standard element uses the hook. The decorations of the standard features,
14//! such as a theorem's heading and its closing mark, are placed when the
15//! document is lowered for a backend, not by this hook.
16//!
17//! # How the hook is called
18//!
19//! The layout step calls the hook once for every node of the element that it
20//! reaches outside an [opaque
21//! region](crate::guide::concepts_overview#opaque-regions), from the root
22//! downwards, before its own default handling of the node. The hook either lays
23//! out the node itself and returns the nodes it staged (built into the new
24//! tree), or returns [`Structuring::Default`] to leave the node to the default
25//! handling. The hook runs while the paragraph around its node is being built,
26//! so it lays out its node's own content and never the paragraph around it.
27//!
28//! The hook works through two values it receives:
29//!
30//! - [`StructureCx`], the context through which the pass stages nodes;
31//! - [`BlockStructurer`], the operations of the layout step that the hook may
32//! call (lay out a run of nodes as blocks or as inline content, apply the
33//! default handling to a node, rebuild a node around a new body, create a
34//! node, report a diagnostic). A staged node cannot be read back, so the
35//! hook builds its result from these operations rather than by editing a
36//! tree.
37//!
38//! A node the hook creates is a [`SynthesizedNode`]: a one-node tree of its own,
39//! so that it is a real node reference whose block role can be read like any
40//! node's, and which can be placed in a run of nodes given to
41//! [`BlockStructurer::build_blocks`] or [`BlockStructurer::build_inline`]. Those
42//! two operations stage it when they lay out the run. A created node that is
43//! never placed has no place in the structured tree: the pass reports it
44//! ([`DecoratorWithoutHome`](super::error::DecoratorWithoutHome)) and drops it.
45//! [`RegionLayout`] tells the hook whether its node is placed between blocks or
46//! inside inline content.
47//!
48//! A feature attaches the hook to its element by the trait-object type, like
49//! every aspect: `.with::<dyn BlockStructure>(Arc::new(implementation))`.
50
51use std::fmt;
52use std::sync::Arc;
53
54use techy::core::Lang;
55use techy::core::node::{BuildId, NodeKind, NodeRef, NodeTree, NodeTreeBuilder};
56use techy::source::{Source, SourceSpan};
57use techy::transform::RestageContext;
58
59use super::error::StructureError;
60use crate::model::element::ElementSpec;
61use crate::lang::flm::Flm;
62use crate::lang::mint::FlmSynthesizedSpec;
63use crate::lang::origin::{FlmDiagnostic, FlmSource};
64
65/// The context through which the block-structure pass, a
66/// [`BlockTransparent`](super::transparent::BlockTransparent) aspect and a
67/// [`BlockStructure`] hook stage nodes: techy's restage context
68/// ([`RestageContext`]) over the FLM language.
69///
70/// To *stage* a node is to build it into the new tree that the walk is
71/// producing; a staged node is known by its [`BuildId`] and cannot be read
72/// back. The two unit type parameters say that FLM trees carry no
73/// annotations.
74pub type StructureCx<'t> = RestageContext<'t, Flm, (), ()>;
75
76/// What a [`BlockStructure`] hook returns for its node: leave it to the
77/// default handling, or replace it by nodes the hook staged.
78#[derive(Debug)]
79pub enum Structuring {
80 /// Leave the node to the default handling of the layout step, the same as
81 /// [`BlockStructurer::default`]: each argument laid out by its declared
82 /// layout, the body by the body declaration, and the node rebuilt around
83 /// them.
84 Default,
85 /// The hook staged the node's replacement itself, through the
86 /// [`BlockStructurer`] or the context: these staged nodes take the node's
87 /// place among its siblings, in this order. An empty list removes the
88 /// node.
89 Emit(Vec<BuildId>),
90}
91
92/// The block-structure hook: the aspect an element carries to lay out its own
93/// content during the layout step of the [block-structure pass](super).
94///
95/// [`structure`](BlockStructure::structure) is called once for every node of
96/// the element that the layout step reaches outside an opaque region, from the
97/// root downwards, before the default handling of that node. The hook lays out
98/// the node through the operations of `bs` and returns the nodes it staged, or
99/// returns [`Structuring::Default`] to leave the node to the default handling.
100/// See the [module documentation](self) for what a hook is for.
101///
102/// A hook must not give its *own* node to a run it lays out, because the pass
103/// would call the hook again on it. It lays out the node's parts instead, with
104/// [`body_run`](BlockStructurer::body_run),
105/// [`default`](BlockStructurer::default) and
106/// [`with_body`](BlockStructurer::with_body).
107///
108/// The [tree contract](super::check) binds what a hook produces: a body or an
109/// argument that its declaration lays out as blocks must hold only paragraphs,
110/// block-level nodes and comments, and one laid out inline must hold no
111/// paragraph.
112pub trait BlockStructure: Send + Sync {
113 /// Lays out `node`, or leaves it to the default handling.
114 ///
115 /// `cx` is the context to stage nodes through, and `bs` the operations of
116 /// the layout step.
117 ///
118 /// # Errors
119 ///
120 /// The hook returns
121 /// [`StructureError::hook`](super::error::StructureError::hook) for a
122 /// failure of its own, and passes on unchanged the error of a
123 /// [`BlockStructurer`] operation that failed. Either error ends the pass and
124 /// leaves no tree, so a problem in the *document* is reported as a
125 /// diagnostic through [`diagnose`](BlockStructurer::diagnose) instead.
126 fn structure(
127 &self,
128 node: NodeRef<'_, Flm>,
129 cx: &mut StructureCx<'_>,
130 bs: &mut dyn BlockStructurer,
131 ) -> Result<Structuring, StructureError>;
132}
133
134/// Where a hook's node is placed in the content being laid out, as
135/// [`BlockStructurer::region`] returns it.
136///
137/// This is the position of the node, not the region layout of the [content
138/// region](super) that holds it (both are defined in the module
139/// documentation): a node inside a paragraph gets `Inline` even when the paragraph is part of a
140/// content region laid out as blocks, and a hook is never called inside an
141/// opaque region.
142#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
143pub enum RegionLayout {
144 /// The node is placed directly in a content region laid out as blocks,
145 /// on its own between the paragraphs. This is where a node whose block
146 /// role is [`Block`](crate::model::aspects::BlockRole::Block) goes.
147 Blocks,
148 /// The node is inside inline content: inside a paragraph, or in a content
149 /// region laid out inline.
150 Inline,
151}
152
153/// A node created by a block-structure hook through
154/// [`BlockStructurer::synthesize_callable`], or by a
155/// [`BlockTransparent`](super::transparent::BlockTransparent) aspect through
156/// [`BlockCutter::synthesize_callable`](super::transparent::BlockCutter::synthesize_callable):
157/// a callable node with no arguments, no node slots (techy's `ParsedSlot`, the
158/// parts of a node's content outside its arguments, such as an environment's
159/// body) and no content, normally of an
160/// element declared with
161/// [`SyntaxDef::Synthesized`](crate::lang::mint::SyntaxDef::Synthesized), which
162/// no document can write (the operation does not check this). Its span is an empty span on a
163/// synthesized source created at the span of the node the hook or aspect was
164/// called on.
165///
166/// The node is held in a one-node tree of its own until it is staged. A hook
167/// gives [`node`](SynthesizedNode::node) to a run passed to
168/// [`BlockStructurer::build_blocks`] or [`BlockStructurer::build_inline`]; an
169/// aspect stages it with [`BlockCutter::carry`](super::transparent::BlockCutter::carry)
170/// or in a run passed to
171/// [`BlockCutter::restage_and_classify`](super::transparent::BlockCutter::restage_and_classify).
172pub struct SynthesizedNode {
173 tree: NodeTree<Flm>,
174}
175
176impl SynthesizedNode {
177 /// Builds the one-node tree of a callable of `element` at `node`: no
178 /// arguments, no slots, no content, an empty span on a source synthesized
179 /// at `node`'s span, and `node`'s parsing state. Only the two walks of the
180 /// pass call this; an element obtains the value from
181 /// [`BlockStructurer::synthesize_callable`] or
182 /// [`BlockCutter::synthesize_callable`](super::BlockCutter::synthesize_callable).
183 pub(crate) fn mint(
184 node: &NodeRef<'_, Flm>,
185 element: &Arc<ElementSpec>,
186 ) -> Result<SynthesizedNode, StructureError> {
187 let spec = Arc::new(FlmSynthesizedSpec::new(Arc::clone(element)));
188 let description = format!("{} (synthesized by block structuring)", element.name);
189 let source: Arc<FlmSource> = Arc::new(Source::synthesized(
190 String::new(),
191 description,
192 node.span().clone(),
193 ));
194 let span = SourceSpan::new(&source, 0..0);
195 let state = Arc::clone(node.parsing_state());
196 let mut builder: NodeTreeBuilder<Flm> = NodeTreeBuilder::new();
197 let kind = NodeKind::callable(spec.callable_data());
198 let ext = Flm::make_node_ext(&kind, &span, &state, builder.staged_children(&[]))?;
199 let id = builder.add(kind, span, state, Vec::new(), ext, ())?;
200 let tree = builder.finish(id)?;
201 Ok(SynthesizedNode { tree })
202 }
203
204 /// The created node, as a reference to place in a run given to
205 /// [`BlockStructurer::build_blocks`] or [`BlockStructurer::build_inline`].
206 pub fn node(&self) -> NodeRef<'_, Flm> {
207 self.tree.root()
208 }
209
210 /// The element the node carries.
211 pub fn element(&self) -> &Arc<ElementSpec> {
212 &self.tree.root().ext().element
213 }
214}
215
216impl fmt::Debug for SynthesizedNode {
217 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218 f.debug_struct("SynthesizedNode")
219 .field("element", &self.element().name)
220 .finish()
221 }
222}
223
224/// The operations of the layout step that a [`BlockStructure`] hook may call.
225///
226/// The layout step itself implements this trait and hands itself to the hook,
227/// so a hook lays out content exactly as the pass does, without access to the
228/// pass's internal state. Every operation that lays out a run of nodes stages
229/// its result through the context and returns the staged nodes; the hook
230/// assembles them into its result ([`Structuring::Emit`]).
231///
232/// # Errors
233///
234/// Every operation that stages fails with [`StructureError`] when an operation
235/// of techy's tree builder fails, when the content is nested too deeply, or
236/// when the hook of a node inside the laid-out content fails;
237/// [`body_run`](BlockStructurer::body_run) and
238/// [`with_body`](BlockStructurer::with_body) also fail with
239/// [`StructureError::NoBody`] for a node with no body slot. A node's body slot
240/// is the node slot marked by its body marker as the node's body, such as an
241/// environment's body (see [`FlmNodeExts`](crate::lang::flm::FlmNodeExts)); a
242/// node slot (techy's `ParsedSlot`) is a part of a node's content outside its
243/// arguments.
244pub trait BlockStructurer {
245 /// Lays out `run`, a run of sibling nodes, as blocks and returns the staged
246 /// nodes: every maximal stretch of inline content becomes a paragraph,
247 /// each block-level node is placed on its own, the paragraph-break markers
248 /// end paragraphs and are removed, comments are kept, block decorators are
249 /// placed by their [`Placement`](crate::model::aspects::Placement), and the
250 /// text is resolved with the whitespace at the edges of each paragraph
251 /// removed. A run whose nodes were parsed in math mode, and a run that
252 /// stands in a verbatim group or an opaque wrapper or begins with one, is
253 /// an [opaque region](crate::guide::concepts_overview#opaque-regions) and
254 /// is copied unchanged instead.
255 ///
256 /// The staged nodes are paragraphs, block-level nodes and comments. A
257 /// container the hook builds to hold them must therefore be a node of an
258 /// element whose block role is [`Block`](crate::model::aspects::BlockRole::Block):
259 /// a `{…}` group holds inline content only, and the
260 /// [tree-contract checker](super::check) reports a paragraph inside one.
261 fn build_blocks(
262 &mut self,
263 cx: &mut StructureCx<'_>,
264 run: &[NodeRef<'_, Flm>],
265 ) -> Result<Vec<BuildId>, StructureError>;
266
267 /// Lays out `run`, a run of sibling nodes, as inline content and returns
268 /// the staged nodes: no paragraph is built, adjacent text is merged and its
269 /// whitespace collapsed, and the whitespace at the edges of the run is kept.
270 /// A block-level node in the run is kept where it is and reported
271 /// ([`BlockInInline`](super::error::BlockInInline)); a paragraph break is
272 /// read as one space and reported
273 /// ([`ParbreakInInline`](super::error::ParbreakInInline), with the context
274 /// `run`). A run parsed in math mode, and a run that stands in a verbatim
275 /// group or an opaque wrapper or begins with one, is copied unchanged
276 /// instead.
277 fn build_inline(
278 &mut self,
279 cx: &mut StructureCx<'_>,
280 run: &[NodeRef<'_, Flm>],
281 ) -> Result<Vec<BuildId>, StructureError>;
282
283 /// Applies the default handling of the layout step to `node` and returns
284 /// the staged nodes: the handling a node receives when its element has no
285 /// hook, or when the hook returns [`Structuring::Default`].
286 ///
287 /// The arguments of a callable node are laid out by their declared layouts
288 /// ([`ArgLayout`](crate::lang::mint::ArgLayout); inline by default), and
289 /// its body by the element's body declaration
290 /// ([`BodyLayout`](crate::lang::mint::BodyLayout)): as blocks or inline
291 /// where the declaration says so, and otherwise by the element's block role
292 /// (as blocks for an element whose role is
293 /// [`Block`](crate::model::aspects::BlockRole::Block), inline otherwise). A
294 /// verbatim body, a body under an opaque wrapper and a body read in math
295 /// mode are copied unchanged, and so is an argument whose content stands
296 /// in a verbatim group or an opaque wrapper. The content of a `{…}` group
297 /// is laid out inline. Mathematics groups, verbatim groups and opaque
298 /// wrappers are copied unchanged.
299 fn default(
300 &mut self,
301 cx: &mut StructureCx<'_>,
302 node: &NodeRef<'_, Flm>,
303 ) -> Result<Vec<BuildId>, StructureError>;
304
305 /// Returns the content nodes of `node`'s body slot, as a run to lay out
306 /// with [`build_blocks`](BlockStructurer::build_blocks) or
307 /// [`build_inline`](BlockStructurer::build_inline). Nothing is staged.
308 ///
309 /// # Errors
310 ///
311 /// [`StructureError::NoBody`] when the node has no body slot.
312 fn body_run<'t>(
313 &mut self,
314 node: &NodeRef<'t, Flm>,
315 ) -> Result<Vec<NodeRef<'t, Flm>>, StructureError>;
316
317 /// Stages a copy of the callable `node` whose body slot holds `body`, nodes
318 /// the hook staged, and returns it. The arguments and the other slots
319 /// receive the default handling; what surrounds the body's content in the
320 /// source (the delimiters of the slot and the text around them) is copied
321 /// unchanged.
322 ///
323 /// # Errors
324 ///
325 /// [`StructureError::NoBody`] when the node has no body slot.
326 fn with_body(
327 &mut self,
328 cx: &mut StructureCx<'_>,
329 node: &NodeRef<'_, Flm>,
330 body: Vec<BuildId>,
331 ) -> Result<BuildId, StructureError>;
332
333 /// Creates a node of `element` at `node`: a callable node with no
334 /// arguments, no slots and no content, with an empty span on a source
335 /// synthesized at `node`'s span, and `node`'s parsing state.
336 ///
337 /// Place [`SynthesizedNode::node`] in a run given to
338 /// [`build_blocks`](BlockStructurer::build_blocks) or
339 /// [`build_inline`](BlockStructurer::build_inline); the element's block role
340 /// then decides where the node goes in the paragraph:
341 /// `BlockDecorator(Leads)` for a run-in heading, `BlockDecorator(Trails)`
342 /// for a mark that ends a statement
343 /// ([`Placement`](crate::model::aspects::Placement)). A created node that
344 /// is never placed by one of those two operations is reported
345 /// ([`DecoratorWithoutHome`](super::error::DecoratorWithoutHome)) and
346 /// dropped when the hook returns; a copy the hook stages itself through the
347 /// context does not count as placed.
348 ///
349 /// `element` should be declared with
350 /// [`SyntaxDef::Synthesized`](crate::lang::mint::SyntaxDef::Synthesized)
351 /// (no syntax), so that no document can write it. This operation cannot
352 /// check that, because an element value does not carry its syntax
353 /// declaration, and it creates a node of any element.
354 fn synthesize_callable(
355 &mut self,
356 node: &NodeRef<'_, Flm>,
357 element: &Arc<ElementSpec>,
358 ) -> Result<SynthesizedNode, StructureError>;
359
360 /// Adds `diagnostic` to the diagnostics the pass returns to its caller: a
361 /// condition the hook found in the document, at a span of the hook's
362 /// choice. This is how a hook reports a problem in the document without
363 /// ending the pass.
364 fn diagnose(&mut self, diagnostic: FlmDiagnostic);
365
366 /// Returns where the hook's node is placed: directly between blocks, or
367 /// inside inline content (a paragraph, or a content region laid out
368 /// inline).
369 fn region(&self) -> RegionLayout;
370}