flm_core/lang/rewrites/blocks/error.rs
1//! The problems the [block-structure pass](super) reports: the conditions it
2//! recovers from, and the failure that leaves no tree.
3//!
4//! The pass reports a problem in one of two ways, as every part of FLM does
5//! (see [diagnostics](crate::guide::concepts_overview#diagnostics)):
6//!
7//! - A problem in the document's content is reported as an Error diagnostic
8//! and the pass goes on: it returns the structured tree, and the diagnostic
9//! marks the place of the problem. The conditions are [`BlockInInline`],
10//! [`ParbreakInInline`] and [`DecoratorWithoutHome`]; each one's
11//! documentation says what the pass does with the content.
12//! - A problem after which the pass cannot continue ends the pass with a
13//! [`StructureError`], and there is **no tree**. One Error diagnostic
14//! explains the absent tree ([`StructureError::diagnostic`]): the
15//! [recursion guard](crate::lang::guard) refused the nesting depth, the pass
16//! or an element's aspect broke an invariant of the tree builder, or no
17//! [worker thread](crate::lang::guard::on_worker_thread) could be created.
18//!
19//! No input document makes the pass panic.
20//!
21//! The pass has an error type of its own rather than
22//! [`RewriteError`](crate::core::stage::RewriteError), the error type of
23//! rewrite stages, because the pass is a
24//! plain function that can be called with no stage around it, and
25//! `RewriteError` belongs to the stages. The rewrite stage of the `blocks`
26//! feature ([`crate::stdlib::features::blocks`]) converts one into the other
27//! with [`StructureError::diagnostic`].
28
29use std::fmt;
30
31use techy::core::node::{NodeBuildError, NodeTree};
32use techy::error::{Diagnostic, DiagnosticInfo};
33use techy::transform::RestageError;
34
35use crate::model::names::ElementName;
36use crate::lang::flm::Flm;
37use crate::lang::guard::NestingTooDeep;
38use crate::lang::origin::FlmDiagnostic;
39
40// --- recovered conditions -------------------------------------------------------------
41
42/// Condition `flm.blocks.block-in-inline`: a node whose element has the block
43/// role [`Block`](crate::model::aspects::BlockRole::Block) is placed in a
44/// [content region](super) (a run of sibling nodes laid out together) laid out
45/// inline, such as the top level of a fragment laid out
46/// [`Inline`](crate::model::doc::FragmentLayout::Inline), a `{…}` group, an
47/// argument laid out inline, or a body laid out inline.
48///
49/// Recovery: the node is kept where it is written, among the inline content;
50/// the diagnostic is placed at the node. A lowering rule that renders
51/// such a node differently in an inline content region asks
52/// [`stands_in_blocks`](super::stands_in_blocks).
53#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
54#[diagnostic(
55 id = "flm.blocks.block-in-inline",
56 message = "Block-level element ‘{element}’ may not be placed inside inline content"
57)]
58pub struct BlockInInline {
59 /// The stable name of the node's element.
60 pub element: String,
61}
62
63/// Condition `flm.blocks.parbreak-in-inline`: a paragraph break (a blank line)
64/// is written in a [content region](super) (a run of sibling nodes laid out
65/// together) laid out inline: a `{…}` group, an argument
66/// laid out inline, a body laid out inline, or the top level of a fragment laid
67/// out [`Inline`](crate::model::doc::FragmentLayout::Inline).
68///
69/// Recovery: the paragraph break is read as one space; the diagnostic is
70/// placed at the blank line.
71#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
72#[diagnostic(
73 id = "flm.blocks.parbreak-in-inline",
74 message = "Paragraph breaks may not be placed inside inline content"
75)]
76pub struct ParbreakInInline {
77 /// The kind of content region the paragraph break was found in: `group`,
78 /// `argument`, `body`, `fragment` (the top level), `list` (the content of a
79 /// container node inside inline content), or `run` (a run of nodes that a
80 /// block-structure hook laid out).
81 pub context: String,
82}
83
84/// Condition `flm.blocks.decorator-without-home`: an element's
85/// [block-structure hook](super::hook::BlockStructure) created a node through
86/// [`BlockStructurer::synthesize_callable`](super::hook::BlockStructurer::synthesize_callable)
87/// and returned without placing that node in any run of nodes it laid out, so
88/// the node has no place in the structured tree.
89///
90/// This is a programming error in the hook. It is reported as a diagnostic
91/// rather than as a failure, so that one faulty element does not make the
92/// document lose its tree.
93///
94/// Recovery: the node is dropped; the diagnostic is placed at the node whose
95/// hook created it.
96#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
97#[diagnostic(
98 id = "flm.blocks.decorator-without-home",
99 message = "Misconfigured block-structure hook ‘{hook}’: The hook failed to place a node for ‘{element}’"
100)]
101pub struct DecoratorWithoutHome {
102 /// The stable name of the created node's element.
103 pub element: String,
104 /// The stable name of the element whose hook created the node.
105 pub hook: String,
106}
107
108// --- failures ---------------------------------------------------------------------------
109
110/// Condition `flm.blocks.structure-failed`: the pass failed for a reason in the
111/// program, not in the document: the pass itself, an element's
112/// [`BlockTransparent`](super::transparent::BlockTransparent) aspect or its
113/// [block-structure hook](super::hook::BlockStructure) broke an invariant of
114/// techy's tree builder, or the aspect or the hook reported a failure of its
115/// own.
116///
117/// Recovery: none; there is no tree. [`StructureError::diagnostic`] builds this
118/// diagnostic at the root of the tree and the caller records it in place of
119/// the tree.
120#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
121#[diagnostic(
122 id = "flm.blocks.structure-failed",
123 message = "Block and paragraph structure processing failed: {detail}"
124)]
125pub struct StructureFailed {
126 /// What failed, as text: the [`Display`](fmt::Display) text of the
127 /// [`StructureError`].
128 pub detail: String,
129}
130
131/// Condition `flm.blocks.worker-thread-unavailable`: the pass was not run,
132/// because the calling thread is not a [worker
133/// thread](crate::lang::guard::on_worker_thread) and the operating system
134/// refused to create one.
135///
136/// The pass runs only on a worker thread, whose declared stack size gives the
137/// [recursion guard](crate::lang::guard) its budget, so that the guard can
138/// refuse deeply nested content with a diagnostic before the stack overflows.
139///
140/// Recovery: none; there is no tree.
141#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
142#[diagnostic(
143 id = "flm.blocks.worker-thread-unavailable",
144 message = "Failed to create a thread with a sufficiently large stack: {detail}"
145)]
146pub struct NoWorkerThread {
147 /// The operating system's error.
148 pub detail: String,
149}
150
151/// The failure of a call to the [block-structure pass](super::pass) that
152/// returned no tree.
153///
154/// [`structure`](super::structure) and
155/// [`structure_with_guard`](super::structure_with_guard) return it; an element's
156/// [`BlockTransparent`](super::transparent::BlockTransparent) aspect or
157/// [block-structure hook](super::hook::BlockStructure) returns it to report a
158/// failure of its own ([`StructureError::cut`], [`StructureError::hook`]), and
159/// the operations of [`BlockCutter`](super::transparent::BlockCutter) and
160/// [`BlockStructurer`](super::hook::BlockStructurer) return it when they fail.
161///
162/// Every variant corresponds to one Error diagnostic, which
163/// [`diagnostic`](StructureError::diagnostic) builds, so an absent tree is
164/// always explained.
165#[derive(Debug, Clone)]
166pub enum StructureError {
167 /// The [recursion guard](crate::lang::guard) refused to descend further:
168 /// the content is nested too deeply. The diagnostic carries
169 /// [`NestingTooDeep`] (`flm.blocks.nesting-too-deep`).
170 NestingTooDeep {
171 /// The guard's explanation of which limit was reached.
172 detail: String,
173 },
174 /// The pass was not run, because the operating system refused to create a
175 /// worker thread. The diagnostic carries [`NoWorkerThread`]
176 /// (`flm.blocks.worker-thread-unavailable`).
177 WorkerThread {
178 /// The operating system's error.
179 detail: String,
180 },
181 /// An operation of techy's tree builder failed: the pass, an aspect or a
182 /// hook broke an invariant of the builder, or asked for an edit of an
183 /// argument or a node slot (techy's `ParsedSlot`, a part of a node's
184 /// content outside its arguments) that the builder refuses. The diagnostic
185 /// carries [`StructureFailed`].
186 ///
187 /// The error is boxed because the type is recursive: techy's restage error
188 /// can hold an error of the walk, which is this type again.
189 Restage(Box<RestageError<StructureError>>),
190 /// An element's [block-structure hook](super::hook::BlockStructure)
191 /// reported a failure of its own ([`StructureError::hook`]). The diagnostic
192 /// carries [`StructureFailed`].
193 Hook {
194 /// The element whose hook failed.
195 element: ElementName,
196 /// The hook's explanation.
197 detail: String,
198 },
199 /// A block-structure hook asked for the body of a node that has no body
200 /// slot (the node slot marked by its body marker as the node's body, such
201 /// as an environment's body; see
202 /// [`FlmNodeExts`](crate::lang::flm::FlmNodeExts)), through
203 /// [`body_run`](super::hook::BlockStructurer::body_run) or
204 /// [`with_body`](super::hook::BlockStructurer::with_body). This is a
205 /// programming error in the hook. The diagnostic carries
206 /// [`StructureFailed`].
207 NoBody {
208 /// The element of the node that has no body slot: the node the hook
209 /// passed to `body_run` or `with_body`, which is not always the node
210 /// the hook is attached to.
211 element: ElementName,
212 },
213 /// An element's [`BlockTransparent`](super::transparent::BlockTransparent)
214 /// aspect reported a failure of its own ([`StructureError::cut`]), or
215 /// called an operation of [`BlockCutter`](super::transparent::BlockCutter)
216 /// wrongly, for example asked it to rebuild a part the node does not have.
217 /// The diagnostic carries [`StructureFailed`].
218 Cut {
219 /// The element whose aspect failed.
220 element: ElementName,
221 /// What failed.
222 detail: String,
223 },
224}
225
226impl StructureError {
227 /// Returns a [`StructureError::Hook`] for the element `element` whose
228 /// block-structure hook failed, with the hook's explanation `detail`. A hook
229 /// returns this to end the pass; a problem in the document is reported
230 /// through [`BlockStructurer::diagnose`](super::hook::BlockStructurer::diagnose)
231 /// instead.
232 pub fn hook(element: ElementName, detail: impl Into<String>) -> StructureError {
233 StructureError::Hook {
234 element,
235 detail: detail.into(),
236 }
237 }
238
239 /// Returns a [`StructureError::Cut`] for the element `element` whose
240 /// [`BlockTransparent`](super::transparent::BlockTransparent) aspect
241 /// failed, with the aspect's explanation `detail`. An aspect returns this to
242 /// end the pass; a problem in the document is reported through
243 /// [`BlockCutter::diagnose`](super::transparent::BlockCutter::diagnose)
244 /// instead.
245 pub fn cut(element: ElementName, detail: impl Into<String>) -> StructureError {
246 StructureError::Cut {
247 element,
248 detail: detail.into(),
249 }
250 }
251
252 /// Returns the Error diagnostic that explains the absent tree, positioned at
253 /// the root of `tree`, the tree the pass was called on. A rewrite stage
254 /// records it in place of that tree.
255 ///
256 /// [`StructureError::NestingTooDeep`] gives the condition
257 /// [`NestingTooDeep`], and [`StructureError::WorkerThread`] the condition
258 /// [`NoWorkerThread`]; every other variant gives [`StructureFailed`], with
259 /// this error's [`Display`](fmt::Display) text as its detail.
260 pub fn diagnostic(&self, tree: &NodeTree<Flm>) -> FlmDiagnostic {
261 let span = tree.root().span().clone();
262 match self {
263 StructureError::NestingTooDeep { detail } => {
264 Diagnostic::error(NestingTooDeep::new(detail.clone()), span)
265 }
266 StructureError::WorkerThread { detail } => {
267 Diagnostic::error(NoWorkerThread::new(detail.clone()), span)
268 }
269 other => Diagnostic::error(StructureFailed::new(other.to_string()), span),
270 }
271 }
272}
273
274impl fmt::Display for StructureError {
275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276 match self {
277 StructureError::NestingTooDeep { detail } => {
278 write!(f, "Content too deeply nested: {detail}")
279 }
280 StructureError::WorkerThread { detail } => {
281 write!(f, "The operating system failed to create a thread with a sufficiently large stack: {detail}")
282 }
283 StructureError::Restage(error) => write!(f, "Tree restaging failed: {error}"),
284 StructureError::Hook { element, detail } => {
285 write!(
286 f,
287 "The block-structure hook of ‘{element}’ failed: {detail}"
288 )
289 }
290 StructureError::NoBody { element } => {
291 write!(
292 f,
293 "Misconfigured block-structure hook: ‘{element}’ has no body"
294 )
295 }
296 StructureError::Cut { element, detail } => {
297 write!(f, "Block and paragraph structure processing failed for ‘{element}’: {detail}")
298 }
299 }
300 }
301}
302
303impl std::error::Error for StructureError {}
304
305impl From<RestageError<StructureError>> for StructureError {
306 /// Converts techy's restage error as techy documents it for a walk that
307 /// calls itself again: an error of the walk itself is returned unchanged,
308 /// a refusal of the recursion guard becomes
309 /// [`NestingTooDeep`](StructureError::NestingTooDeep), and any other error
310 /// is boxed as [`Restage`](StructureError::Restage).
311 fn from(error: RestageError<StructureError>) -> StructureError {
312 match error {
313 RestageError::Visitor(error) => error,
314 RestageError::DescentLimitExceeded { detail, .. } => {
315 StructureError::NestingTooDeep { detail }
316 }
317 other => StructureError::Restage(Box::new(other)),
318 }
319 }
320}
321
322impl From<NodeBuildError> for StructureError {
323 /// Wraps a failure of techy's tree builder as
324 /// [`Restage`](StructureError::Restage).
325 fn from(error: NodeBuildError) -> StructureError {
326 StructureError::Restage(Box::new(RestageError::Build(error)))
327 }
328}