Skip to main content

flm_core/lang/rewrites/
input.rs

1//! The splicing pass: [`splice`], a plain function over a tree that replaces
2//! the node of every `\input` command by the content of the included file,
3//! when the parse read that file.
4//!
5//! When a parse reads `\input{file}` and the host supplies the file, the parse
6//! reads the file's content and places it in a node slot of the command's node
7//! (techy's `ParsedSlot`, a part of a node's content outside its arguments,
8//! such as an environment's body), the slot
9//! [`ATTACHED_SLOT`](crate::lang::input::ATTACHED_SLOT) (see
10//! [`crate::lang::input`]). This pass removes that node and puts the included
11//! nodes in its place, among the sibling nodes that held the command. A
12//! paragraph begun before the command therefore continues into the included
13//! content and out of it again. The included nodes keep their spans, which
14//! point into the included file. An `\input` command inside the included
15//! content is replaced in the same way, at every depth.
16//!
17//! Two kinds of `\input` node have no attached content and stay in the tree
18//! unchanged: a command whose file was not brought in (the parse reported the
19//! problem), and the command of a heading input, which places the included
20//! file as a tree of its own ([`crate::lang::input::is_placing`]).
21//!
22//! The pass runs before every other rewrite, so that user definitions, block
23//! structure and every later stage see the included content as part of the
24//! surrounding text. The `input` feature ([`crate::stdlib::features::input`])
25//! places the pass in a plan as its rewrite stage `flm.input.splice`.
26
27use std::sync::Arc;
28
29use techy::core::node::{NodeRef, NodeTree};
30use techy::error::{Diagnostic, DiagnosticInfo};
31use techy::transform::{Restage, RestageContext, RestageError, RestageVisitor};
32
33use crate::lang::flm::Flm;
34use crate::lang::guard::{self, GuardPolicy, NestingTooDeep};
35use crate::lang::input::attached_content;
36use crate::lang::origin::{FlmDiagnostic, FlmSpan};
37use crate::lang::parse::WorkerThreadUnavailable;
38
39/// Condition `flm.input.splice-failed`: the splicing pass failed for a reason
40/// that lies in the program, not in the document (an operation of techy's tree
41/// builder refused, for example), and returned no tree.
42///
43/// Recovery: none. [`SpliceFailure::Failed`] carries this diagnostic, which
44/// is recorded in place of the absent tree.
45#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
46#[diagnostic(
47    id = "flm.input.splice-failed",
48    message = "inserting the content of included files into the document failed: {detail}"
49)]
50pub struct SpliceFailed {
51    /// The failure, as text.
52    pub detail: String,
53}
54
55/// The failure of a call to [`splice`] that returned no tree.
56///
57/// Each variant carries the one Error diagnostic that explains the absent tree,
58/// positioned at the root of the tree the pass was called on;
59/// [`diagnostic`](SpliceFailure::diagnostic) returns it for every variant.
60/// The `input` feature's rewrite stage records it in place of the tree.
61#[derive(Debug)]
62pub enum SpliceFailure {
63    /// The [recursion guard](crate::lang::guard) refused to descend further:
64    /// the content is nested too deeply. The diagnostic carries
65    /// [`NestingTooDeep`] (`flm.blocks.nesting-too-deep`).
66    NestingTooDeep(FlmDiagnostic),
67    /// The pass failed for a reason in the program, not in the document. The
68    /// diagnostic carries [`SpliceFailed`] (`flm.input.splice-failed`).
69    Failed(FlmDiagnostic),
70    /// The pass was not attempted: the calling thread is not a [worker
71    /// thread](crate::lang::guard::on_worker_thread) and the operating system
72    /// refused to create one. The diagnostic carries
73    /// [`WorkerThreadUnavailable`] (`flm.lang.worker-thread-unavailable`).
74    WorkerThread(FlmDiagnostic),
75}
76
77impl SpliceFailure {
78    /// The Error diagnostic that explains the absent tree.
79    pub fn diagnostic(&self) -> &FlmDiagnostic {
80        match self {
81            SpliceFailure::NestingTooDeep(diagnostic)
82            | SpliceFailure::Failed(diagnostic)
83            | SpliceFailure::WorkerThread(diagnostic) => diagnostic,
84        }
85    }
86}
87
88/// Replaces, throughout `tree`, the node of every `\input` command by the
89/// content of the included file (for each command whose file the parse read),
90/// and returns the new tree.
91///
92/// `tree` is a parsed tree, or a tree an earlier rewrite produced. The nodes of
93/// the included content take the place of the command's node among its
94/// siblings, at every depth; the module documentation says which `\input`
95/// nodes stay. A tree with no `\input` command comes back as an identical copy.
96///
97/// The walk runs under the recursion-guard policy `guard`, normally the built
98/// language's ([`BuiltLang::guard`](crate::lang::BuiltLang::guard)). It runs on
99/// a [worker thread](crate::lang::guard::on_worker_thread): on the calling
100/// thread when that thread is already one, otherwise on a thread created for
101/// the call.
102///
103/// # Errors
104///
105/// [`SpliceFailure`] when no tree could be produced: the content is nested too
106/// deeply for the guard, the operating system refused to create a worker
107/// thread, or an operation of the tree builder failed. Each variant carries the
108/// one Error diagnostic to record in place of the tree.
109pub fn splice(tree: &NodeTree<Flm>, guard: GuardPolicy) -> Result<Arc<NodeTree<Flm>>, SpliceFailure> {
110    let at = tree.root().span().clone();
111    let run = || run_pass(tree, guard);
112    match guard::on_worker_thread(run) {
113        Ok(result) => result,
114        Err(error) => Err(SpliceFailure::WorkerThread(Diagnostic::error(
115            WorkerThreadUnavailable::new(error.to_string()),
116            at,
117        ))),
118    }
119}
120
121/// The pass itself, on a thread that meets the worker-thread requirement.
122fn run_pass(tree: &NodeTree<Flm>, policy: GuardPolicy) -> Result<Arc<NodeTree<Flm>>, SpliceFailure> {
123    let mut pass = SplicePass;
124    match guard::restager(&mut pass, policy).restage(tree) {
125        Ok(spliced) => Ok(Arc::new(spliced)),
126        Err(error) => Err(failure(error, tree.root().span().clone())),
127    }
128}
129
130/// The [`SpliceFailure`] for a failed restage (techy's walk that builds the new
131/// tree), positioned at `at`: a refusal of the guard, possibly wrapped in the
132/// visitor's error, becomes [`SpliceFailure::NestingTooDeep`]; anything else
133/// becomes [`SpliceFailure::Failed`].
134fn failure(error: RestageError<RestageFailure>, at: FlmSpan) -> SpliceFailure {
135    let refusal = match &error {
136        RestageError::DescentLimitExceeded { detail, .. } => Some(detail.clone()),
137        RestageError::Visitor(RestageFailure(inner)) => match inner.as_ref() {
138            RestageError::DescentLimitExceeded { detail, .. } => Some(detail.clone()),
139            _ => None,
140        },
141        _ => None,
142    };
143    match refusal {
144        Some(detail) => SpliceFailure::NestingTooDeep(Diagnostic::error(NestingTooDeep::new(detail), at)),
145        None => SpliceFailure::Failed(Diagnostic::error(SpliceFailed::new(error.to_string()), at)),
146    }
147}
148
149/// A failure of a context operation inside the visitor, boxed so that the
150/// visitor can carry it through its own error type.
151#[derive(Debug)]
152struct RestageFailure(Box<RestageError<RestageFailure>>);
153
154impl std::fmt::Display for RestageFailure {
155    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
156        write!(f, "{}", self.0)
157    }
158}
159
160impl From<RestageError<RestageFailure>> for RestageFailure {
161    fn from(error: RestageError<RestageFailure>) -> RestageFailure {
162        RestageFailure(Box::new(error))
163    }
164}
165
166/// The visitor of the restage: at an `\input` node with attached content it
167/// stages (builds into the new tree) the included nodes in place of the node;
168/// every other node is copied and its children visited. It has no state.
169struct SplicePass;
170
171impl RestageVisitor<Flm, (), ()> for SplicePass {
172    type Error = RestageFailure;
173
174    fn restage(
175        &mut self,
176        node: NodeRef<'_, Flm>,
177        cx: &mut RestageContext<'_, Flm, (), ()>,
178    ) -> Result<Restage<()>, RestageFailure> {
179        let Some(content) = attached_content(&node) else { return Ok(Restage::Descend(())) };
180        let mut ids = Vec::new();
181        for child in content {
182            ids.extend(cx.restage_subtree(child, self)?);
183        }
184        Ok(Restage::Emit(ids))
185    }
186}