flm_core/stdlib/features/input/mod.rs
1//! The `input` feature: `\input{file}`, which brings the content of another file into
2//! the document where the command is written.
3//!
4//! # What an author writes, and what it produces
5//!
6//! An author writes `\input{chapter.flm}` to include the file `chapter.flm`. The
7//! argument is the reference to the file, as plain characters; the embedding
8//! program's input resolver ([`InputResolver`](crate::lang::InputResolver)) finds and
9//! reads the file it refers to (the `flm` program reads it relative to the folder of
10//! the file that holds the command). The guide to the language describes the command
11//! for authors ([including files](crate::guide::language_syntax#including-files)).
12//!
13//! An included file is one of two kinds, as its front matter declares (see [content
14//! inputs and heading
15//! inputs](crate::lang::input#content-inputs-and-heading-inputs)):
16//!
17//! - A **content input** continues the text around the command: its content is parsed
18//! where the command is written, and every output shows it as if it had been written
19//! there. A paragraph begun before the command continues into the included content.
20//! - A **heading input** opens with a heading and becomes a tree of its own in the
21//! document ([`crate::model::assemble`]). The command stays in the tree as a block,
22//! and every output writes the included tree where the command is.
23//!
24//! When the file could not be brought in (its reference is not plain characters, no
25//! file is found, the file includes itself, …), the parse reports the problem at the
26//! command, and every output shows a mark where the content is missing (the dropped
27//! mark `flm.pres.dropped`,
28//! [`lowering::error`](crate::stdlib::backends::lowering::error), which gives the
29//! reference).
30//!
31//! # How a parse handles the command
32//!
33//! The feature declares the command as an inclusion macro of the language
34//! ([`SyntaxDef::Inclusion`]), whose one argument is the reference. What happens while
35//! the document is parsed (the embedding program asked for the file, the content of a
36//! content input parsed where the command is written) is done by the language layer
37//! ([`crate::lang::input`]).
38//!
39//! # The splicing rewrite
40//!
41//! A rewrite stage runs before the document's trees are frozen and turns one tree into
42//! another ([`RewriteStage`]). The feature's rewrite stage [`SPLICE`]
43//! (`flm.input.splice`) replaces every command whose file was brought in by the file's
44//! content, in place of the command among its sibling nodes
45//! ([`crate::lang::rewrites::input`]), and publishes the trees as [`SPLICED`]
46//! (`flm.input.spliced`). It runs before the rewrites of the user definitions and of
47//! the block structure, so that they, and every later stage, see one text: a paragraph
48//! begun before the command continues into the included content, a list written there
49//! nests in the list around the command, and a user definition used there is
50//! expanded. The capability `flm.input.spliced` is a member of the collection
51//! [`flm.validated`](crate::stdlib::VALIDATED), which every standard workflow
52//! demands, so the rewrite runs in every plan of a standard workflow.
53//!
54//! # The lowering rule
55//!
56//! Only two kinds of `\input` command remain in the trees after the splicing rewrite,
57//! and the rule [`RULE`] (`flm.input.lower.default`, [`InputRule`]), the default on
58//! every backend, lowers both:
59//!
60//! - **The command of a heading input.** The command places the included file's tree.
61//! For each such command in the rewritten trees, the run records the tree the command
62//! places, and the document order enters that tree at the command
63//! ([`crate::core::run::order`]). The rule asks which tree
64//! the command places ([`Lowerer::placement`]) and lowers the command to a
65//! [`flm.pres.subtree`](crate::stdlib::backends::pres::SUBTREE) node that gives that
66//! tree, which every output writes where the command is.
67//! - **A command whose file was not brought in.** The parse reported the problem, and
68//! the rule lowers the command to a
69//! [`flm.pres.dropped`](crate::stdlib::backends::pres::DROPPED) mark that gives the
70//! reference (`\input{chapter.flm}`), on every output, so that a reader sees where
71//! content is missing.
72//!
73//! A command of a heading input that a rewrite copied (a user definition whose
74//! template writes twice the argument that holds the command) places its file at its
75//! first copy only, because a file is placed at one place of the document. The run
76//! reports each other copy (`flm.run.placed-twice`), and the rule lowers it to the same
77//! dropped mark.
78//!
79//! # Items
80//!
81//! - The feature: [`Input`], [`feature`], [`FEATURE`].
82//! - The element: [`ELEMENT`] (`flm.input`), and the argument role
83//! [`PATH_ARG_ROLE`] (`flm.input.path`), which states that an argument holds
84//! a reference to another file whose content is read in
85//! ([`ArgDef::role`](crate::lang::mint::ArgDef::role)).
86//! - The rewrite stage: [`SPLICE`], [`SPLICED`].
87//! - The lowering rule: [`RULE`], [`InputRule`], [`rule`].
88
89use std::sync::Arc;
90
91use techy::core::node::{NodeRef, NodeTree};
92
93use crate::core::lowering::{
94 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
95 chars_at_lowering,
96};
97use crate::core::plan::PlanCx;
98use crate::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature};
99use crate::core::run::RewriteCx;
100use crate::core::stage::{Needs, RewriteDecl, RewriteError, RewriteStage, TreesTable};
101use crate::lang::input::{is_placing, REFERENCE_ARGUMENT};
102use crate::stdlib::backends::pres::SubtreePayload;
103use crate::lang::mint::{ArgDef, ArgStdKind, ElementDef, SyntaxDef};
104use crate::lang::rewrites::input::{SpliceFailure, splice};
105use crate::lang::{Flm, FlmDiagnostics};
106use crate::model::addr::TreeId;
107use crate::model::aspects::{ApartFromText, BlockRole, BlockRoleAspect, ContentRef};
108use crate::model::element::ElementSpec;
109use crate::model::names::{ElementName, FeatureName, Name};
110use crate::core::data::table::TableName;
111use crate::stdlib::VALIDATED;
112use crate::stdlib::backends::pres::{self, DroppedPayload};
113use crate::stdlib::features::blocks::STRUCTURED;
114use crate::stdlib::features::userdefs::{ALWAYS_EXPANDED, EXPANDED};
115
116/// The feature's registered name, `input`.
117pub const FEATURE: &str = "input";
118
119/// The name of the element of the command `\input`, `flm.input`.
120pub const ELEMENT: &str = "flm.input";
121
122/// The name of the splicing rewrite stage, `flm.input.splice`, which replaces
123/// every command whose file was brought in by the file's content.
124pub const SPLICE: &str = "flm.input.splice";
125
126/// The table of trees that the splicing rewrite publishes, which is also the
127/// capability it provides, `flm.input.spliced`: the content of every included
128/// file is in place of its command, among the command's sibling nodes.
129pub const SPLICED: TableName<TreesTable> = TableName::new("flm.input.spliced");
130
131/// The name of the lowering rule of the command of a heading input and of a
132/// command whose file was not brought in, `flm.input.lower.default`
133/// ([`InputRule`]).
134pub const RULE: &str = "flm.input.lower.default";
135
136/// The argument role of a reference to another file whose content is read
137/// in, `flm.input.path`: the role of the reference argument
138/// ([`REFERENCE_ARGUMENT`]) of `\input`.
139pub const PATH_ARG_ROLE: &str = "flm.input.path";
140
141/// The [`ApartFromText`] aspect of the command: the reference is a file name, not
142/// part of the words of the text around it.
143#[derive(Debug, Clone, Copy)]
144struct InputText;
145
146impl ApartFromText for InputText {
147 fn apart_from_text(&self, _node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
148 vec![ContentRef::ArgumentNamed(REFERENCE_ARGUMENT.to_string())]
149 }
150}
151
152/// The block role of the command: a command that places a heading input's tree
153/// is a block; any other is inline content (the command of a content input is
154/// replaced by its content before the block-structure pass runs).
155#[derive(Debug, Clone, Copy)]
156struct InputBlockRole;
157
158impl BlockRoleAspect for InputBlockRole {
159 fn block_role(&self, node: &NodeRef<'_, Flm>) -> BlockRole {
160 if is_placing(node) { BlockRole::Block } else { BlockRole::DEFAULT }
161 }
162}
163
164/// Returns the element value of the command: the element [`ELEMENT`] with its
165/// block role ([`InputBlockRole`]) and its [`ApartFromText`] aspect
166/// ([`InputText`]).
167fn element() -> Arc<ElementSpec> {
168 Arc::new(
169 ElementSpec::new(ELEMENT)
170 .docs(
171 "`\\input{file}`: the content of another file, brought in where the command \
172 is written.",
173 )
174 .with::<dyn BlockRoleAspect>(Arc::new(InputBlockRole))
175 .with::<dyn ApartFromText>(Arc::new(InputText)),
176 )
177}
178
179/// The splicing rewrite stage [`SPLICE`]. See the [module
180/// documentation](self#the-splicing-rewrite).
181struct SpliceStage;
182
183impl RewriteStage for SpliceStage {
184 fn decl(&self) -> RewriteDecl {
185 RewriteDecl::new(SPLICE, SPLICED.name()).docs(
186 "Replaces every `\\input` whose file was brought in by the file's content, in place \
187 of the command among its sibling nodes. Publishes the trees as \
188 `flm.input.spliced`; runs before the expansion of user definitions and before \
189 block structure.",
190 )
191 }
192
193 /// Ordering only: the stage runs before the rewrites of the user definitions
194 /// and of the block structure, for those of them the registry declares.
195 fn needs(&self, cx: &PlanCx<'_>) -> Needs {
196 // The order is declared here, by edges of this stage: no other feature
197 // knows of file inclusion, so none orders itself after this rewrite.
198 let mut needs = Needs::new();
199 for later in [ALWAYS_EXPANDED.name(), EXPANDED.name(), STRUCTURED.name()] {
200 if cx.registry().cap_id(later).is_some() {
201 needs = needs.before(later);
202 }
203 }
204 needs
205 }
206
207 fn rewrite(
208 &self,
209 _tree_id: TreeId,
210 tree: &Arc<NodeTree<Flm>>,
211 cx: &RewriteCx<'_>,
212 _diags: &mut FlmDiagnostics,
213 ) -> Result<Arc<NodeTree<Flm>>, RewriteError> {
214 splice(tree, cx.registry().lang().guard()).map_err(|failure| match failure {
215 SpliceFailure::NestingTooDeep(diagnostic) => RewriteError::NestingTooDeep(diagnostic),
216 SpliceFailure::Failed(diagnostic) | SpliceFailure::WorkerThread(diagnostic) => {
217 RewriteError::Failed(diagnostic)
218 }
219 })
220 }
221}
222
223/// The implementation of the lowering rule [`RULE`]: it lowers the command of a
224/// heading input to a `flm.pres.subtree` node that gives the tree the command
225/// places, and a command whose file was not brought in to a `flm.pres.dropped`
226/// mark that gives the reference. The command of a content input never reaches
227/// the rule, because the splicing rewrite replaced it. See the [module
228/// documentation](self#the-lowering-rule).
229#[derive(Debug, Default, Clone, Copy)]
230pub struct InputRule;
231
232impl Lower for InputRule {
233 fn lower(
234 &self,
235 node: NodeRef<'_, Flm>,
236 cx: &mut LowerCx<'_>,
237 lw: &mut dyn Lowerer,
238 ) -> Result<Lowering, LowerError> {
239 if is_placing(&node) {
240 if let Some(tree) = lw.placement() {
241 let subtree = lw.pres_with(cx, &ElementName::from(pres::SUBTREE), SubtreePayload { tree }, Vec::new())?;
242 return Ok(Lowering::Emit(vec![subtree]));
243 }
244 }
245 let reference = match node.argument_content_nodes_named(REFERENCE_ARGUMENT) {
246 Ok(Some(content)) => chars_at_lowering(content.iter())?.unwrap_or_default(),
247 _ => String::new(),
248 };
249 // The mark's condition is the element's name: the parse's diagnostic is
250 // not at hand when lowering.
251 let mark = DroppedPayload {
252 condition: Name::from(ELEMENT),
253 detail: format!("\\input{{{reference}}}"),
254 };
255 let dropped = lw.pres_with(cx, &ElementName::from(pres::DROPPED), mark, Vec::new())?;
256 Ok(Lowering::Emit(vec![dropped]))
257 }
258}
259
260/// Returns the lowering rule [`RULE`], the default of the element on every
261/// backend.
262pub fn rule() -> LoweringRule {
263 LoweringRule::new(
264 RULE,
265 ELEMENT,
266 LoweringDecl::new().produces(pres::SUBTREE).produces(pres::DROPPED),
267 Arc::new(InputRule),
268 DefaultMark::Everywhere,
269 )
270 .docs(
271 "an `\\input` that places a heading input's tree lowers to a `flm.pres.subtree` node \
272 that gives the tree; one whose file was not brought in, to a `flm.pres.dropped` mark \
273 that gives the reference",
274 )
275}
276
277/// The `input` feature: it registers the command `\input`, the splicing
278/// rewrite stage [`SPLICE`] and its membership in the collection
279/// `flm.validated`, and the lowering rule [`RULE`]. See the [module
280/// documentation](self).
281#[derive(Debug, Default, Clone, Copy)]
282pub struct Input;
283
284impl FlmFeature for Input {
285 fn info(&self) -> FeatureInfo {
286 FeatureInfo::new(FEATURE, "Included files").docs(
287 "`\\input{file}`: the content of another file, parsed where the command is written \
288 and put in place of the command by the rewrite `flm.input.splice`, which \
289 publishes `flm.input.spliced`.",
290 )
291 }
292
293 fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
294 let owner: FeatureName = b.feature().clone();
295 b.argument_role(
296 PATH_ARG_ROLE,
297 "A reference to another file, usually its path, whose content is read in where \
298 the command is written.",
299 )?;
300 b.element(
301 ElementDef::new(
302 owner,
303 ["input"],
304 SyntaxDef::Inclusion {
305 args: vec![ArgDef::named(REFERENCE_ARGUMENT, ArgStdKind::CharsGroup)
306 .docs(
307 "The reference to the file, as plain characters; the embedding \
308 program's input resolver finds the file it refers to.",
309 )
310 .role(PATH_ARG_ROLE)],
311 },
312 element(),
313 )
314 .docs("Brings in the content of another file where the command is written."),
315 )?;
316 b.element_type_text(
317 ELEMENT,
318 "The content of another file, brought in where the command that names the file is \
319 written.",
320 )?;
321 b.rewrite_stage(Arc::new(SpliceStage))?;
322 b.collection_member(VALIDATED, SPLICED.name())?;
323 b.lowering_rule(rule())?;
324 Ok(())
325 }
326}
327
328/// Returns the [`Input`] feature, ready to be listed in a package entry.
329pub fn feature() -> Arc<dyn FlmFeature> {
330 Arc::new(Input)
331}