Skip to main content

flm_core/lang/
input.rs

1//! This module provides file inclusion with the `\input{file}` command: the
2//! [`InputResolver`] trait, which a program that embeds FLM implements to read
3//! the included files, and the specification of inclusion macros
4//! ([`InputSpec`]), along with the error conditions that are reported for an
5//! inclusion.
6//!
7//! # Reading the included files
8//!
9//! FLM performs no input or output, so the library cannot read a file itself. A
10//! program that embeds FLM provides an *input resolver*, an object that
11//! implements [`InputResolver`]. For each `\input` command, the library calls
12//! the input resolver with the reference written in the document, for instance
13//! `parts/intro.flm`. The input resolver finds and reads the file, reads the
14//! front matter of the file, and returns the content and the information from
15//! the front matter as an [`IncludedFile`].
16//!
17//! You set the input resolver in the inputs of a registry, with
18//! [`RegistryInputs::input_resolver`](crate::core::registry::RegistryInputs::input_resolver),
19//! or for a single parse, with
20//! [`ParseOptions::input_resolver`](crate::lang::ParseOptions::input_resolver).
21//! The `flm` program provides an input resolver that reads files relative to
22//! the folder of the including file.
23//!
24//! The library keeps track of which file includes which. It reports a file
25//! that includes itself and a chain of inclusions that is too deep, so the
26//! input resolver does not need to remember earlier calls.
27//!
28//! # Content inputs and heading inputs
29//!
30//! An included file is either a content input or a heading input. The input
31//! resolver selects the kind with the field [`IncludedFile::heading`], usually
32//! according to the front matter of the file.
33//!
34//! - A *content input* continues the text around the `\input` command. Its
35//!   content is parsed at the place of the command, as if it were written
36//!   there. For instance, a paragraph can begin in the including file and end
37//!   in the included file.
38//! - A *heading input* is a part of the document with a heading of its own,
39//!   such as a chapter kept in a file. The input resolver provides the heading
40//!   as an [`InputHeading`]. The library parses the heading input as a separate
41//!   tree that begins with the heading, and places this tree in the document at
42//!   the `\input` command. Only the assembly of a whole document
43//!   ([`crate::model::assemble`]) places such trees. A heading input can
44//!   therefore be included only in a whole document, and only once.
45//!
46//! # The content of a content input in the tree
47//!
48//! The content of a content input is parsed under the parsing state in effect
49//! at the `\input` command, with the parsing settings of the file
50//! ([`IncludedFile::parsing`]) applied. A change that the included content
51//! makes to the parsing state does not apply after the command.
52//!
53//! The parsed content is stored in the node slot [`ATTACHED_SLOT`] of the node
54//! of the `\input` command. A *node slot* (techy's `ParsedSlot`) is a part of
55//! the content of a node that is not an argument, such as the body of an
56//! environment. The nodes of the included content have spans in the included
57//! file, and the node of the command has its span in the including file.
58//! [`attached_content`] returns the included content of such a node.
59//!
60//! The splicing pass ([`crate::lang::rewrites::input`]) runs before every
61//! other rewrite pass, and replaces the node of each `\input` command with the
62//! included content. The later passes and stages therefore process the
63//! included content as if it were written in the including file.
64//!
65//! For a heading input, the node of the `\input` command has the empty node
66//! slot [`PLACED_SLOT`] instead, and [`is_placing`] returns `true` for this
67//! node.
68//!
69//! # Errors
70//!
71//! When a file cannot be included, the parser of the `\input` command reports
72//! an error at the command, and the command includes nothing. With the standard
73//! [`input` feature](crate::stdlib::features::input), the command then expands
74//! to a dropped mark (`flm.pres.dropped`). The following errors prevent the
75//! inclusion:
76//!
77//! - [`InputReferenceNotPlain`]: the reference is not plain text.
78//! - [`InputUnavailable`]: no input resolver is set.
79//! - [`InputUnreadable`]: the input resolver failed to provide the file.
80//! - [`InputIncludesItself`]: the file includes itself.
81//! - [`InputTooDeep`]: the chain of inclusions is too deep.
82//! - [`InputInDefinition`]: the command is written in a user definition.
83//! - [`InputHeadingOutsideDocument`], [`InputHeadingCommandInvalid`] and
84//!   [`InputPlacedTwice`]: a heading input cannot be included.
85//!
86//! The file is still included after the errors [`IncludedFrontMatterProblem`]
87//! and [`InputHeadingLabelInvalid`].
88
89use std::any::Any;
90use std::fmt;
91use std::sync::Arc;
92
93use techy::core::constructs::{
94    parse_declared_arguments, ChildStateSpec, ConstructParser, ConstructParserResult, Invocation,
95    ParseContext, PlainCharsError, StopSpec,
96};
97use techy::core::node::{
98    BuildId, ChildRegion, ContentNodes, NodeKind, NodeRef, ParsedArguments, ParsedSlot,
99    ParsedSlots, SlotRole,
100};
101use techy::core::specs::{ArgumentSpec, CallableSpec};
102use techy::core::token::TokenEdge;
103use techy::core::{ParseDriver, ParsingState, ParsingStateDelta};
104use techy::error::{DiagnosticInfo, ParseError};
105use techy::latexlike::BodyMarker;
106use techy::serialize::SerializableObject;
107use techy::source::SourceSpan;
108
109use crate::lang::flm::Flm;
110use crate::lang::mint::specs::FlmCallable;
111use crate::lang::origin::{FlmOrigin, FlmSource, FlmSpan};
112use crate::lang::rules::FlmParsing;
113
114/// The name of the argument of an inclusion macro that contains the reference
115/// to the included file (`reference`).
116///
117/// An argument with this name must be declared for every inclusion macro
118/// ([`InputSpec::new`]).
119pub const REFERENCE_ARGUMENT: &str = "reference";
120
121/// The name of the node slot that contains the included content of a content
122/// input (`attached`).
123///
124/// The node of an `\input` command has this slot when the command included a
125/// content input. A node slot is a part of the content of a node that is not
126/// an argument; see [the module
127/// documentation](self#the-content-of-a-content-input-in-the-tree).
128pub const ATTACHED_SLOT: &str = "attached";
129
130/// The name of the empty node slot that marks the node of an `\input` command
131/// that included a heading input (`placed`).
132///
133/// The tree of the heading input is placed in the document at this node
134/// ([`is_placing`]).
135pub const PLACED_SLOT: &str = "placed";
136
137/// The maximum depth of an included file (32).
138///
139/// The primary file has depth zero, a file that the primary file includes has
140/// depth one, and so on. A file at a greater depth is not included
141/// ([`InputTooDeep`]).
142pub const DEPTH_LIMIT: usize = 32;
143
144// --- what the library asks of a host ----------------------------------------------------
145
146/// An `IncludedFile` contains the content of an included file and the
147/// information that the input resolver read from the front matter of the file.
148///
149/// An [`InputResolver`] returns an `IncludedFile` for each `\input` command.
150/// The fields have defaults, so a resolver that reads no front matter only
151/// sets [`name`](Self::name), [`text`](Self::text) and
152/// [`first_line`](Self::first_line).
153#[derive(Debug, Clone, Default, PartialEq, Eq)]
154pub struct IncludedFile {
155    /// The name that identifies the file, for instance its canonical path.
156    ///
157    /// Diagnostics refer to the file by this name. The library also compares
158    /// names to detect a file that includes itself ([`InputIncludesItself`])
159    /// and a heading input that is included twice ([`InputPlacedTwice`]).
160    /// Therefore, two references to the same file must give the same name, and
161    /// two different files must have different names. The name of the primary
162    /// file is the canonical path of its [origin](crate::lang::FlmOrigin).
163    pub name: String,
164    /// The content of the file, without its front matter.
165    pub text: String,
166    /// The line of the file on which [`text`](Self::text) begins, counted from
167    /// one.
168    ///
169    /// The library uses this number to report a problem in the content at its
170    /// line in the file. For a file without front matter, the value is one.
171    /// The value zero counts as one.
172    pub first_line: usize,
173    /// The parsing settings of the content, if parsing settings are written in
174    /// the file itself, for instance in its front matter.
175    ///
176    /// The value is complete: it contains the `parsing` settings that the
177    /// library passes to [`InputResolver::resolve`], with the settings of the
178    /// file applied over them. With `None`, the content is parsed under the
179    /// parsing state in effect at the `\input` command.
180    pub parsing: Option<FlmParsing>,
181    /// The problems that the input resolver found in the front matter of the
182    /// file.
183    ///
184    /// The library reports each problem as an error
185    /// ([`IncludedFrontMatterProblem`]) and still includes the file.
186    pub problems: Vec<IncludedFileProblem>,
187    /// The heading of a heading input, or `None` for a content input.
188    ///
189    /// See [content inputs and heading
190    /// inputs](self#content-inputs-and-heading-inputs) for the two kinds of
191    /// included files.
192    pub heading: Option<InputHeading>,
193}
194
195/// An `InputHeading` describes the heading of a heading input
196/// ([`IncludedFile::heading`]).
197///
198/// The library writes the heading as FLM source before the content of the
199/// file, and parses it with the content. For instance, the heading command
200/// `section`, the title `Methods` and the label `sec:methods` give
201/// `\section{Methods}\label{sec:methods}`. An unnumbered heading uses the
202/// starred form of the command, as in `\section*{Methods}`.
203///
204/// The command is parsed like any command written in the document. The library
205/// does not check that the command is a heading command. It only checks that
206/// [`command`](Self::command) is a valid command name
207/// ([`InputHeadingCommandInvalid`]) and that [`label`](Self::label) contains
208/// no brace ([`InputHeadingLabelInvalid`]).
209#[derive(Debug, Clone, Default, PartialEq, Eq)]
210pub struct InputHeading {
211    /// The name of the heading command, without the backslash, for instance
212    /// `section`.
213    pub command: String,
214    /// The title, as FLM source, for instance `The \emph{Art}`.
215    pub title: String,
216    /// The line and the column of the title in the file, both counted from
217    /// one, or `None` if the title is not written in the file.
218    ///
219    /// The library uses this position to report a problem in the title at its
220    /// place in the file.
221    pub title_at: Option<(usize, usize)>,
222    /// The label of the heading, if the heading has one.
223    pub label: Option<String>,
224    /// Whether the heading is numbered. If `false`, the library writes the
225    /// starred form of the heading command. The default is `false`.
226    pub numbered: bool,
227}
228
229/// An `IncludedFileProblem` describes a problem that an input resolver found
230/// in the front matter of an included file ([`IncludedFile::problems`]).
231///
232/// The library reports the problem as the error
233/// [`IncludedFrontMatterProblem`], at the given line and column of the
234/// included file.
235#[derive(Debug, Clone, PartialEq, Eq)]
236pub struct IncludedFileProblem {
237    /// The line of the problem, counted from one.
238    pub line: usize,
239    /// The column of the problem, counted from one.
240    pub column: usize,
241    /// The message of the diagnostic. Write it like the messages of the
242    /// library: state directly what is wrong, as in `Unknown key ‘title2’`.
243    pub message: String,
244}
245
246/// The error that an input resolver returns when it fails to provide the file
247/// of an `\input` command, for instance because the file does not exist.
248///
249/// The library reports the failure as the error [`InputUnreadable`], whose
250/// message contains [`message`](Self::message).
251#[derive(Debug, Clone, PartialEq, Eq)]
252pub struct InputError {
253    /// The description of the failure. It should give the file that the input
254    /// resolver tried to read.
255    pub message: String,
256}
257
258impl InputError {
259    /// Returns an error with the description `message`.
260    pub fn new(message: impl Into<String>) -> InputError {
261        InputError { message: message.into() }
262    }
263}
264
265impl fmt::Display for InputError {
266    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267        f.write_str(&self.message)
268    }
269}
270
271impl std::error::Error for InputError {}
272
273/// An input resolver finds and reads the files that `\input` commands refer
274/// to. A program that embeds FLM implements this trait, because the library
275/// performs no input or output itself.
276///
277/// You set the input resolver in the inputs of a registry, with
278/// [`RegistryInputs::input_resolver`](crate::core::registry::RegistryInputs::input_resolver),
279/// or for a single parse, with
280/// [`ParseOptions::input_resolver`](crate::lang::ParseOptions::input_resolver).
281/// If no input resolver is set, the library reports each `\input` command as
282/// an error ([`InputUnavailable`]) and includes nothing. See the [module
283/// documentation](self) for how included files are parsed.
284///
285/// The library calls [`resolve`](Self::resolve) once for each `\input` command
286/// that it parses. The method receives three arguments:
287///
288/// - `reference`: the reference to the file, as written in the document. The
289///   input resolver decides how to find the file from the reference, usually
290///   relative to the including file.
291/// - `including`: the [name](IncludedFile::name) of the file that contains
292///   the `\input` command, or `None` if the content does not come from a file.
293///   For the primary file, the name is the canonical path of its
294///   [origin](crate::lang::FlmOrigin).
295/// - `parsing`: the parsing settings in effect at the `\input` command. In an
296///   included file, these are the settings under which the library parses the
297///   file.
298///
299/// If parsing settings are written in the file itself, the input resolver
300/// applies them over `parsing` and returns the result in
301/// [`IncludedFile::parsing`].
302///
303/// The library keeps track of which file includes which, and of the parsing
304/// settings of each file. An input resolver therefore does not need to
305/// remember earlier calls.
306///
307/// An input resolver must be `Send` and `Sync`, because the library can call
308/// it from several threads. If your input resolver records the files that it
309/// reads, store the record behind a lock, for instance a `Mutex`.
310///
311/// # Examples
312///
313/// The following input resolver provides files stored in memory. It sets the
314/// name, the content and the first line of each file. The other fields of
315/// [`IncludedFile`] keep their defaults, so each file is a content input
316/// without parsing settings of its own.
317///
318/// ```
319/// use std::collections::HashMap;
320///
321/// use flm_core::lang::{FlmParsing, IncludedFile, InputError, InputResolver};
322///
323/// struct InMemory {
324///     files: HashMap<String, String>,
325/// }
326///
327/// impl InputResolver for InMemory {
328///     fn resolve(
329///         &self,
330///         reference: &str,
331///         _including: Option<&str>,
332///         _parsing: &FlmParsing,
333///     ) -> Result<IncludedFile, InputError> {
334///         let text = self
335///             .files
336///             .get(reference)
337///             .ok_or_else(|| InputError::new(format!("no file named ‘{reference}’")))?;
338///         Ok(IncludedFile {
339///             name: reference.to_string(),
340///             text: text.clone(),
341///             first_line: 1,
342///             ..Default::default()
343///         })
344///     }
345/// }
346///
347/// let resolver = InMemory {
348///     files: HashMap::from([(String::from("intro.flm"), String::from("Hello."))]),
349/// };
350/// let file = resolver.resolve("intro.flm", None, &FlmParsing::default()).unwrap();
351/// assert_eq!(file.text, "Hello.");
352/// assert!(resolver.resolve("missing.flm", None, &FlmParsing::default()).is_err());
353/// ```
354pub trait InputResolver: Send + Sync {
355    /// Finds and reads the file that `reference` refers to, and returns its
356    /// content and the information from its front matter. The [trait
357    /// documentation](InputResolver) describes the arguments.
358    ///
359    /// # Errors
360    ///
361    /// Returns an [`InputError`] if the file cannot be found or read. The
362    /// library reports the error at the `\input` command ([`InputUnreadable`])
363    /// and includes nothing.
364    fn resolve(
365        &self,
366        reference: &str,
367        including: Option<&str>,
368        parsing: &FlmParsing,
369    ) -> Result<IncludedFile, InputError>;
370}
371
372// --- the conditions -------------------------------------------------------------------
373
374/// The error that is reported when the argument of `\input` is not plain text
375/// (`flm.input.reference-not-plain`).
376///
377/// The argument must consist of characters only, as in
378/// `\input{parts/intro.flm}`.
379///
380/// Reported by the parser of `\input` when it parses the command. The command
381/// includes no file. With the standard [`input`
382/// feature](crate::stdlib::features::input), the command expands to a dropped
383/// mark (`flm.pres.dropped`).
384#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
385#[diagnostic(
386    id = "flm.input.reference-not-plain",
387    message = "Invalid argument to ‘\\input’, expected plain text only"
388)]
389pub struct InputReferenceNotPlain;
390
391/// The error that is reported when a document uses `\input` and no input
392/// resolver is set (`flm.input.unavailable`).
393///
394/// The library reads included files through an [`InputResolver`], which the
395/// program that processes the document must provide. The [`InputResolver`]
396/// documentation describes how to set one.
397///
398/// Reported by the parser of `\input` when it parses the command. The command
399/// includes no file. With the standard [`input`
400/// feature](crate::stdlib::features::input), the command expands to a dropped
401/// mark (`flm.pres.dropped`).
402#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
403#[diagnostic(
404    id = "flm.input.unavailable",
405    message = "Cannot process ‘\\input{{{reference}}}’: No input source resolver configured for this document"
406)]
407pub struct InputUnavailable {
408    /// The reference, as written.
409    pub reference: String,
410}
411
412/// The error that is reported when the input resolver fails to provide the
413/// file of an `\input` command (`flm.input.unreadable`).
414///
415/// The input resolver returns an [`InputError`], for instance because the file
416/// does not exist or cannot be read. The message of the diagnostic contains
417/// the description of the failure from the [`InputError`].
418///
419/// Reported by the parser of `\input` when it parses the command. The command
420/// includes no file. With the standard [`input`
421/// feature](crate::stdlib::features::input), the command expands to a dropped
422/// mark (`flm.pres.dropped`).
423#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
424#[diagnostic(
425    id = "flm.input.unreadable",
426    message = "Source input ‘{reference}’ nonexistent or unreadable: {detail}"
427)]
428pub struct InputUnreadable {
429    /// The reference, as written.
430    pub reference: String,
431    /// The description of the failure ([`InputError::message`]).
432    pub detail: String,
433}
434
435/// The error that is reported when a file includes itself, directly or
436/// through other files (`flm.input.includes-itself`).
437///
438/// The library compares the [name](IncludedFile::name) of the file that an
439/// `\input` command refers to with the names of the including file, the file
440/// that includes it, and so on up to the primary file.
441///
442/// Reported by the parser of `\input` at the command that would include the
443/// file again. The command includes no file. With the standard [`input`
444/// feature](crate::stdlib::features::input), the command expands to a dropped
445/// mark (`flm.pres.dropped`).
446#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
447#[diagnostic(
448    id = "flm.input.includes-itself",
449    message = "Refusing recursive inclusion of ‘{file}’"
450)]
451pub struct InputIncludesItself {
452    /// The [name](IncludedFile::name) of the file.
453    pub file: String,
454}
455
456/// The error that is reported when an included file would have a depth
457/// greater than [`DEPTH_LIMIT`] (`flm.input.too-deep`).
458///
459/// The primary file has depth zero, a file that the primary file includes has
460/// depth one, and so on.
461///
462/// Reported by the parser of `\input` when it parses the command. The command
463/// includes no file. With the standard [`input`
464/// feature](crate::stdlib::features::input), the command expands to a dropped
465/// mark (`flm.pres.dropped`).
466#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
467#[diagnostic(
468    id = "flm.input.too-deep",
469    message = "Input depth limit ({limit} levels) reached while processing inclusion of ‘{file}’"
470)]
471pub struct InputTooDeep {
472    /// The maximum depth, [`DEPTH_LIMIT`].
473    pub limit: usize,
474    /// The [name](IncludedFile::name) of the file that the `\input` command
475    /// refers to.
476    pub file: String,
477}
478
479/// The error that is reported when `\input` is written in the definition of a
480/// user-defined command or environment (`flm.input.in-definition`).
481///
482/// This is the case when `\input` is written in the template of a [user
483/// definition](crate::lang::rewrites::userdefs::Definition), or in the default
484/// value of one of its arguments.
485///
486/// Reported by the parser of `\input` when it parses the command. The command
487/// includes no file. With the standard [`input`
488/// feature](crate::stdlib::features::input), the command expands to a dropped
489/// mark (`flm.pres.dropped`).
490#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
491#[diagnostic(
492    id = "flm.input.in-definition",
493    message = "‘\\input’ must not appear in the template or default argument values of a \
494               user-defined command or environment"
495)]
496pub struct InputInDefinition;
497
498/// The error that is reported for a problem that the input resolver found in
499/// the front matter of an included file (`flm.input.front-matter`).
500///
501/// The input resolver returns the problem as an [`IncludedFileProblem`]. The
502/// message of the diagnostic is the message of the [`IncludedFileProblem`].
503///
504/// Reported by the parser of `\input`, at the line and column of the problem
505/// in the included file. The file is still included.
506#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
507#[diagnostic(id = "flm.input.front-matter", message = "{message}")]
508pub struct IncludedFrontMatterProblem {
509    /// The message from the input resolver ([`IncludedFileProblem::message`]).
510    pub message: String,
511}
512
513/// The error that is reported when a heading input is included a second time
514/// in a document (`flm.input.placed-twice`).
515///
516/// The tree of a [heading input](self#content-inputs-and-heading-inputs) is
517/// placed in the document at the `\input` command, so a heading input can be
518/// included only once. Two `\input` commands include the same file when the
519/// input resolver returns the same [name](IncludedFile::name) for both.
520///
521/// Reported by the parser of `\input` at the second command. The second
522/// command includes no file. With the standard [`input`
523/// feature](crate::stdlib::features::input), it expands to a dropped mark
524/// (`flm.pres.dropped`).
525#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
526#[diagnostic(
527    id = "flm.input.placed-twice",
528    message = "Duplicate heading-mode inclusion of ‘{file}’"
529)]
530pub struct InputPlacedTwice {
531    /// The [name](IncludedFile::name) of the file.
532    pub file: String,
533}
534
535/// The error that is reported when a heading input is included outside the
536/// assembly of a whole document (`flm.input.heading-outside-document`).
537///
538/// The tree of a [heading input](self#content-inputs-and-heading-inputs) is
539/// placed in the document at the `\input` command. Only the assembly of a
540/// whole document ([`crate::model::assemble`]) places such trees. Content that
541/// is parsed on its own, for instance with
542/// [`parse_fragment`](crate::lang::parse_fragment), is not part of a document.
543/// A site generator, for instance, parses each field of its data in this way.
544///
545/// Reported by the parser of `\input` when it parses the command. The command
546/// includes no file. With the standard [`input`
547/// feature](crate::stdlib::features::input), the command expands to a dropped
548/// mark (`flm.pres.dropped`).
549#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
550#[diagnostic(
551    id = "flm.input.heading-outside-document",
552    message = "Heading-mode inclusion of ‘{file}’ is only possible in a whole document"
553)]
554pub struct InputHeadingOutsideDocument {
555    /// The [name](IncludedFile::name) of the file.
556    pub file: String,
557}
558
559/// The error that is reported when the assembly of a document does not find
560/// the node of the `\input` command of a heading input
561/// (`flm.input.placement-lost`).
562///
563/// When the parser of `\input` includes a heading input, it records the file
564/// for the assembly ([`crate::model::assemble`]) and adds the node of the
565/// command to the tree. The assembly then places the tree of the heading input
566/// at this node. A document cannot cause this error: a missing node indicates
567/// a fault in the library or in an extension.
568///
569/// Reported by the assembly, at the `\input` command. The tree of the heading
570/// input is not placed in the document.
571#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
572#[diagnostic(
573    id = "flm.input.placement-lost",
574    message = "Misconfigured input processing: The node of a heading-mode ‘\\input’ for ‘{file}’ was not found in the final document tree"
575)]
576pub struct InputPlacementLost {
577    /// The [name](IncludedFile::name) of the file.
578    pub file: String,
579}
580
581/// The error that is reported when the heading command of a heading input is
582/// not a valid command name (`flm.input.heading-command`).
583///
584/// The input resolver provides the heading command in
585/// [`InputHeading::command`], usually from the front matter of the included
586/// file. The heading command must be the name of a command without the
587/// backslash, as in `section`. It may contain only the characters that the
588/// parsing settings in effect at the `\input` command allow in a command name.
589///
590/// Reported by the parser of `\input` when it parses the command. The command
591/// includes no file. With the standard [`input`
592/// feature](crate::stdlib::features::input), the command expands to a dropped
593/// mark (`flm.pres.dropped`).
594#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
595#[diagnostic(
596    id = "flm.input.heading-command",
597    message = "Invalid heading command ‘\\{command}’ configured for heading-mode input of ‘{file}’"
598)]
599pub struct InputHeadingCommandInvalid {
600    /// The [name](IncludedFile::name) of the file.
601    pub file: String,
602    /// The heading command, as provided by the input resolver.
603    pub command: String,
604}
605
606
607// ### Why do we have to check that the label doesn't hold a brace??? How is this even a condition??? What's the deal here????
608
609/// The error that is reported when the label of the heading of a heading input
610/// contains a brace (`flm.input.heading-label`).
611///
612/// The input resolver provides the label in [`InputHeading::label`], usually
613/// from the front matter of the included file. The library writes the heading
614/// as FLM source, as in `\section{Methods}\label{sec:methods}`, and parses it. A
615/// brace in the label would change where the argument of `\label` ends.
616/// Therefore, the label must not contain `{` or `}`.
617///
618/// Reported by the parser of `\input` when it parses the command. The file is
619/// still included, and its heading has no label.
620#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
621#[diagnostic(
622    id = "flm.input.heading-label",
623    message = "Invalid label ‘{label}’ specified in heading-mode inclusion of ‘{file}’"
624)]
625pub struct InputHeadingLabelInvalid {
626    /// The [name](IncludedFile::name) of the file.
627    pub file: String,
628    /// The label, as provided by the input resolver.
629    pub label: String,
630}
631
632// --- the record of heading inputs -------------------------------------------------------
633
634/// A `PlacedInput` records a heading input that the parser of `\input`
635/// included. It contains what the assembly of the document needs to parse the
636/// file as a separate tree and to place this tree at the `\input` command.
637#[derive(Debug, Clone)]
638pub(crate) struct PlacedInput {
639    /// The span of the `\input` command in the including file. The assembly
640    /// finds the node of the command by this span.
641    pub(crate) site: FlmSpan,
642    /// The [name](IncludedFile::name) of the file.
643    pub(crate) name: String,
644    /// The content of the file, as a source included from the `\input`
645    /// command.
646    pub(crate) source: Arc<FlmSource>,
647    /// The heading of the heading input.
648    pub(crate) heading: InputHeading,
649    /// The parsing state under which the file is parsed: the state at the
650    /// `\input` command, with the parsing settings of the file applied.
651    pub(crate) state: Arc<ParsingState<Flm>>,
652}
653
654/// `Placements` collects the heading inputs that are included while one
655/// document is assembled, in the order in which they are parsed.
656///
657/// The assembly ([`crate::model::assemble`]) sets a `Placements` on the parse
658/// driver (`FlmDriver::with_placements`), and reads the new records after each
659/// parse. The parser of `\input` reports [`InputHeadingOutsideDocument`] when
660/// the parse driver has no `Placements`.
661#[derive(Debug, Default)]
662pub(crate) struct Placements {
663    records: std::sync::Mutex<Vec<PlacedInput>>,
664}
665
666impl Placements {
667    fn lock(&self) -> std::sync::MutexGuard<'_, Vec<PlacedInput>> {
668        self.records.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
669    }
670
671    /// Returns the number of heading inputs recorded so far.
672    pub(crate) fn len(&self) -> usize {
673        self.lock().len()
674    }
675
676    /// Returns the records with the indices `from..to`, or an empty vector if
677    /// this range is out of bounds.
678    pub(crate) fn range(&self, from: usize, to: usize) -> Vec<PlacedInput> {
679        self.lock().get(from..to).map(<[PlacedInput]>::to_vec).unwrap_or_default()
680    }
681
682    /// Records `placed` and returns `true`, or returns `false` without
683    /// recording if a heading input with the same name was recorded before.
684    fn record(&self, placed: PlacedInput) -> bool {
685        let mut records = self.lock();
686        if records.iter().any(|known| known.name == placed.name) {
687            return false;
688        }
689        records.push(placed);
690        true
691    }
692}
693
694/// Returns the FLM source of the heading of a heading input.
695///
696/// The source has two lines: the heading command on the first line, as in
697/// `\section` or `\section*`, and the title in braces followed by
698/// `\label{label}` on the second line. The origin of the source is the name of
699/// the file, and the source is included from the `\input` command. The line
700/// and column offsets of the source place the title at its position in the
701/// file ([`InputHeading::title_at`]), so that a problem in the title is
702/// reported there. These offsets apply to every line of the source, which is
703/// why the title is on a line of its own.
704///
705/// [`attach`] checks the command name and the label before it records the
706/// heading input, so the source contains exactly one command and its argument.
707pub(crate) fn heading_source(placed: &PlacedInput) -> Arc<FlmSource> {
708    let heading = &placed.heading;
709    let star = if heading.numbered { "" } else { "*" };
710    let mut text = format!("\\{}{star}\n{{{}}}", heading.command, heading.title);
711    if let Some(label) = &heading.label {
712        text.push_str(&format!("\\label{{{label}}}"));
713    }
714    // The heading ends its line, as it would in a file.
715    text.push('\n');
716    // The title stands on the source's second line, after the one-byte `{`.
717    let (line, column) = match heading.title_at {
718        Some((line, column)) => (line.saturating_sub(1), column.saturating_sub(1)),
719        None => (1, 1),
720    };
721    let source = FlmSource::resolved(text, placed.name.as_str(), placed.site.clone())
722        .with_origin(FlmOrigin::new(placed.name.clone()))
723        .with_line_column_number_offsets(line, column);
724    Arc::new(source)
725}
726
727/// Returns whether `name` is a valid command name under `state`: `name` is not
728/// empty, and a command rule of `state` with the escape character `\` accepts
729/// every character of `name` in a command name.
730fn is_command_name(state: &ParsingState<Flm>, name: &str) -> bool {
731    !name.is_empty()
732        && state
733            .rules()
734            .command_rules()
735            .iter()
736            .any(|rule| rule.escape_char == '\\' && name.chars().all(|c| rule.name_chars.contains(c)))
737}
738
739/// The root parser of the tree of a heading input.
740///
741/// The parser parses the heading ([`heading_source`]) and then the content of
742/// the file, both as included sources, so that a problem in either is reported
743/// with the chain of inclusions. The root node contains the nodes of both and
744/// spans the content of the file.
745pub(crate) struct PlacedRoot {
746    pub(crate) heading: Arc<FlmSource>,
747}
748
749impl ConstructParser<Flm> for PlacedRoot {
750    type Output = BuildId;
751
752    fn parse(
753        &mut self,
754        cx: &mut ParseContext<'_, '_, Flm>,
755    ) -> ConstructParserResult<Flm, (BuildId, Option<Box<ParsingStateDelta<Flm>>>)> {
756        let entry = Arc::clone(&cx.state);
757        let source = Arc::clone(cx.here().source());
758        let driver = cx.driver;
759        let mut parser = driver
760            .make_nodes_parser(StopSpec::none(), ChildStateSpec::inherit())
761            .map_err(|error| cx.attach_hook_frames(error))?;
762        let mut nodes = cx.parse_attached_source(Arc::clone(&self.heading), Arc::clone(&entry), &mut *parser)?.nodes;
763        nodes.extend(cx.parse_attached_source(Arc::clone(&source), Arc::clone(&entry), &mut *parser)?.nodes);
764        let whole = SourceSpan::entire(&source);
765        let root = cx
766            .stage_node(NodeKind::list(), whole.clone(), entry, nodes)
767            .map_err(|error| cx.implementation_error(error, whole))?;
768        Ok((root, None))
769    }
770}
771
772// --- the specification ----------------------------------------------------------------
773
774/// An `InputSpec` is the specification of an inclusion macro, such as
775/// `\input`. It contains the arguments of the macro and provides the parser
776/// that includes the file (see the [module documentation](self)).
777///
778/// To define an inclusion macro in a feature, declare an element with the
779/// syntax [`SyntaxDef::Inclusion`](crate::lang::mint::SyntaxDef::Inclusion).
780/// [Minting](crate::lang::mint) then creates the `InputSpec`, and wraps it in
781/// an [`FlmCallable`] like the specification of every macro.
782#[derive(Debug)]
783pub struct InputSpec {
784    arguments: Vec<Arc<ArgumentSpec<Flm>>>,
785}
786
787impl InputSpec {
788    /// Returns the specification of an inclusion macro with the arguments
789    /// `arguments`, in the order in which they are written.
790    ///
791    /// # Errors
792    ///
793    /// Returns an error if no argument is named [`REFERENCE_ARGUMENT`]. The
794    /// error is a description of the declared arguments, which minting embeds
795    /// in the message of its own error.
796    pub fn new(arguments: Vec<Arc<ArgumentSpec<Flm>>>) -> Result<InputSpec, String> {
797        if arguments.iter().any(|argument| argument.name.as_deref() == Some(REFERENCE_ARGUMENT)) {
798            return Ok(InputSpec { arguments });
799        }
800        let names: Vec<String> = arguments
801            .iter()
802            .map(|argument| argument.name.as_deref().map_or_else(|| String::from("<unnamed>"), |n| format!("‘{n}’")))
803            .collect();
804        Err(if names.is_empty() {
805            String::from("no argument declared")
806        } else {
807            format!("declared arguments: {}", names.join(", "))
808        })
809    }
810}
811
812impl SerializableObject<Flm> for InputSpec {}
813
814impl CallableSpec<Flm> for InputSpec {
815    fn arguments(&self) -> &[Arc<ArgumentSpec<Flm>>] {
816        &self.arguments
817    }
818
819    fn make_invocation_parser<'a>(
820        &'a self,
821        invocation: Invocation<'a, Flm>,
822    ) -> Result<Box<dyn ConstructParser<Flm, Output = BuildId> + 'a>, ParseError<FlmOrigin>> {
823        Ok(Box::new(InputParser { invocation }))
824    }
825}
826
827/// Returns whether `node` is the node of an inclusion macro, such as `\input`.
828///
829/// The result does not depend on whether the file was included.
830pub fn is_input(node: &NodeRef<'_, Flm>) -> bool {
831    let Some(spec) = node.spec() else { return false };
832    (&**spec as &dyn Any)
833        .downcast_ref::<FlmCallable>()
834        .is_some_and(|callable| (&**callable.syntax() as &dyn Any).is::<InputSpec>())
835}
836
837/// Returns whether `node` is the node of an inclusion macro that included a
838/// heading input.
839///
840/// The tree of the heading input is placed in the document at this node
841/// ([`DocContent::resolve`](crate::model::doc::DocContent::resolve)).
842pub fn is_placing(node: &NodeRef<'_, Flm>) -> bool {
843    is_input(node) && node.slot_content_nodes_named(PLACED_SLOT).is_ok()
844}
845
846/// Returns the included content of a content input: the nodes in the node
847/// slot [`ATTACHED_SLOT`] of `node`.
848///
849/// Returns `None` if `node` is not the node of an inclusion macro, or if the
850/// macro did not include a content input. The splicing pass
851/// ([`crate::lang::rewrites::input`]) replaces the node of each inclusion macro
852/// with its included content, so this function is useful only on a tree
853/// before this pass.
854pub fn attached_content<'t>(node: &NodeRef<'t, Flm>) -> Option<Vec<NodeRef<'t, Flm>>> {
855    if !is_input(node) {
856        return None;
857    }
858    node.slot_content_nodes_named(ATTACHED_SLOT).ok().map(|nodes| nodes.iter().collect())
859}
860
861// --- the parser -----------------------------------------------------------------------
862
863/// The parser of one invocation of an inclusion macro.
864struct InputParser<'a> {
865    invocation: Invocation<'a, Flm>,
866}
867
868impl ConstructParser<Flm> for InputParser<'_> {
869    type Output = BuildId;
870
871    fn parse(
872        &mut self,
873        cx: &mut ParseContext<'_, '_, Flm>,
874    ) -> ConstructParserResult<Flm, (BuildId, Option<Box<ParsingStateDelta<Flm>>>)> {
875        let token = self.invocation.token;
876        let name = cx.tokens.source_span_between(token, TokenEdge::Start, TokenEdge::End);
877        let (mut children, arguments) = parse_declared_arguments(cx, self.invocation.spec, &name)?;
878        let end = cx.tokens.position_here();
879        let at = cx.source_span_within(&cx.tokens.position_at(token, TokenEdge::Start), &end)?;
880
881        let reference_argument = arguments
882            .iter()
883            .find(|argument| argument.name() == Some(REFERENCE_ARGUMENT))
884            .ok_or_else(|| {
885                cx.implementation_error("an inclusion macro without a reference argument", at.clone())
886            })?;
887        let reference = match cx.argument_content_as_plain_chars(reference_argument, &children) {
888            Ok(text) => text,
889            Err(PlainCharsError::NotPlainCharacters { .. }) => {
890                cx.recover(InputReferenceNotPlain, at.clone())?;
891                None
892            }
893            Err(error) => return Err(cx.implementation_error(error.to_string(), at.clone())),
894        };
895
896        let attached = match reference {
897            Some(reference) => attach(cx, &reference, &at)?,
898            None => Attached::Nothing,
899        };
900        let slots = match attached {
901            Attached::Placed => {
902                let offset = children.len() as u32;
903                ParsedSlots::new(vec![ParsedSlot::new(
904                    ChildRegion::new(offset..offset, ContentNodes::InRegion(0..0)),
905                    PLACED_SLOT,
906                    SlotRole::Hidden,
907                    BodyMarker::not_body(),
908                )])
909            }
910            Attached::Content(nodes) => {
911                let offset = children.len() as u32;
912                let count = nodes.len() as u32;
913                children.extend(nodes);
914                ParsedSlots::new(vec![ParsedSlot::new(
915                    ChildRegion::new(offset..offset + count, ContentNodes::InRegion(0..count)),
916                    ATTACHED_SLOT,
917                    SlotRole::Attached,
918                    BodyMarker::not_body(),
919                )])
920            }
921            Attached::Nothing => ParsedSlots::empty(),
922        };
923        // `Some(&end)`: the node's span is the command in the including file;
924        // the rule of the last child would reach into the included file.
925        let id = cx.stage_invocation(
926            &self.invocation,
927            ParsedArguments::from(arguments),
928            slots,
929            children,
930            Some(&end),
931        )?;
932        // No after-effect: nothing the included content does to the parsing
933        // state reaches past the command.
934        Ok((id, None))
935    }
936}
937
938/// The result of [`attach`] for one `\input` command.
939enum Attached {
940    /// A content input was included. The vector contains the parsed content.
941    Content(Vec<BuildId>),
942    /// A heading input was recorded for the assembly of the document.
943    Placed,
944    /// No file was included, and an error was reported.
945    Nothing,
946}
947
948/// Includes the file that `reference` refers to, for the `\input` command at
949/// the span `at`.
950///
951/// Calls the input resolver and checks the chain of inclusions. Parses the
952/// content of a content input under the parsing state at the command, with the
953/// parsing settings of the file applied. Records a heading input in the
954/// [`Placements`] of the parse driver. Reports each problem with
955/// [`ParseContext::recover`] and returns [`Attached::Nothing`] when the file
956/// cannot be included.
957fn attach(
958    cx: &mut ParseContext<'_, '_, Flm>,
959    reference: &str,
960    at: &FlmSpan,
961) -> ConstructParserResult<Flm, Attached> {
962    let including = at.source().origin();
963    if including.is_definition() {
964        cx.recover(InputInDefinition, at.clone())?;
965        return Ok(Attached::Nothing);
966    }
967    let driver = cx.driver;
968    let Some(resolver) = driver.input_resolver() else {
969        cx.recover(InputUnavailable { reference: reference.to_string() }, at.clone())?;
970        return Ok(Attached::Nothing);
971    };
972    let in_force = Arc::clone(&cx.state.ext().parsing);
973    let file = match resolver.resolve(reference, including.canonical_path(), &in_force) {
974        Ok(file) => file,
975        Err(error) => {
976            let condition =
977                InputUnreadable { reference: reference.to_string(), detail: error.message };
978            cx.recover(condition, at.clone())?;
979            return Ok(Attached::Nothing);
980        }
981    };
982    // The library checks the chain of inclusions, so that no host has to: which
983    // file includes which is a fact of the document, and the host states only
984    // each file's identity, as its name.
985    // The chain: the including source, the source that included it, and so
986    // on up to the primary file, which is at depth zero.
987    let mut depth = 0;
988    for source in at.source().including_sources() {
989        if source.origin().canonical_path() == Some(file.name.as_str()) {
990            cx.recover(InputIncludesItself { file: file.name.clone() }, at.clone())?;
991            return Ok(Attached::Nothing);
992        }
993        depth += 1;
994    }
995    if depth > DEPTH_LIMIT {
996        cx.recover(InputTooDeep { limit: DEPTH_LIMIT, file: file.name.clone() }, at.clone())?;
997        return Ok(Attached::Nothing);
998    }
999    for problem in &file.problems {
1000        let place = FlmSource::resolved(String::new(), reference, at.clone())
1001            .with_origin(FlmOrigin::new(file.name.clone()))
1002            .with_line_column_number_offsets(problem.line, problem.column);
1003        let condition = IncludedFrontMatterProblem { message: problem.message.clone() };
1004        cx.recover(condition, SourceSpan::new(&Arc::new(place), 0..0))?;
1005    }
1006    let source = FlmSource::resolved(file.text, reference, at.clone())
1007        .with_origin(FlmOrigin::new(file.name.clone()))
1008        .with_line_column_number_offsets(file.first_line.max(1), 1);
1009    let name = file.name;
1010    // The file's settings are recorded on the state it is read under, so that
1011    // a command inside it hands them on in turn, and no host has to remember
1012    // them.
1013    let state: Arc<ParsingState<Flm>> = match file.parsing {
1014        Some(parsing) => {
1015            let ext = cx.state.ext().clone().with_parsing(parsing.clone());
1016            cx.derive_state(&parsing.state_delta().ext(ext))?
1017        }
1018        None => Arc::clone(&cx.state),
1019    };
1020    let source = Arc::new(source);
1021    if let Some(mut heading) = file.heading {
1022        let Some(placements) = driver.placements() else {
1023            cx.recover(InputHeadingOutsideDocument { file: name }, at.clone())?;
1024            return Ok(Attached::Nothing);
1025        };
1026        // The heading is composed as text from the command name and the label;
1027        // each must keep that text one command with its arguments.
1028        if !is_command_name(&cx.state, &heading.command) {
1029            cx.recover(InputHeadingCommandInvalid { file: name, command: heading.command }, at.clone())?;
1030            return Ok(Attached::Nothing);
1031        }
1032        if let Some(label) = heading.label.take_if(|label| label.contains(['{', '}'])) {
1033            cx.recover(InputHeadingLabelInvalid { file: name.clone(), label }, at.clone())?;
1034        }
1035        let placed = PlacedInput { site: at.clone(), name: name.clone(), source, heading, state };
1036        if placements.record(placed) {
1037            return Ok(Attached::Placed);
1038        }
1039        cx.recover(InputPlacedTwice { file: name }, at.clone())?;
1040        return Ok(Attached::Nothing);
1041    }
1042    let mut parser = driver
1043        .make_nodes_parser(StopSpec::none(), ChildStateSpec::inherit())
1044        .map_err(|error| cx.attach_hook_frames(error))?;
1045    let outcome = cx.parse_attached_source(source, state, &mut *parser)?;
1046    Ok(Attached::Content(outcome.nodes))
1047}