Skip to main content

flm_core/lang/rewrites/userdefs/
template.rs

1//! The template language and its compiler.
2//!
3//! The **template language** is FLM text with placeholders (`#1`, `#{name}`,
4//! `#{body}`, `#[…]{ref}`), compiled once when the registry is built; a user
5//! definition's template is written in it, and so are number templates, within
6//! templates, list label templates, heading title templates, theorem heading
7//! templates and the defterm lead-in. A **placeholder** is a reference in a
8//! template to an argument, the body, or a name whose content an expansion hook
9//! computes; at expansion it is replaced by the argument's content nodes and
10//! nothing else.
11//!
12//! The template language is the language the registry declares, extended by one
13//! character, `#`, which introduces a placeholder, and by the conditional
14//! commands. A template is parsed once, when the registry is built, under a
15//! parsing state that adds these two to the registry's language
16//! ([`TemplateLanguage`]). The result, a
17//! [`CompiledTemplate`], is a tree whose placeholder nodes are known and checked,
18//! ready to be copied onto a new source at every use; the
19//! [expand pass](super::expand) does that copying.
20//!
21//! The other features that compile templates of their own in this language
22//! each declare their own placeholder names (see [the template language shared by
23//! features](crate::guide::concepts_overview#the-template-language-shared-by-features)).
24//! For authors, the language is described in
25//! [the template language](crate::guide::language_syntax#the-template-language).
26//!
27//! # The placeholder syntax
28//!
29//! - `#1` … `#9`: the numbered arguments. One digit follows `#`, as in TeX:
30//!   `#12` is `#1` followed by `2`, and an argument beyond the ninth is written
31//!   in the braced form, `#{12}`. The numbering starts at the definition's
32//!   declared *argument number offset*, one value for the whole template, so `#1`
33//!   is the argument at index `offset`. The offset is declared beside the
34//!   arguments and is never written in the template.
35//! - `#{name}`: the argument declared with that name; `#{body}`: an
36//!   environment's body; any other name: a placeholder whose content an
37//!   expansion hook of the definition computes.
38//! - `#[…]{name}`: the placeholder `name` with a *substitution argument*, data
39//!   for a placeholder whose content a feature computes; the numbered, named and
40//!   `body` placeholders accept none.
41//! - `##`: a literal `#`.
42//!
43//! **How `#` is recognized.** In a template parse, `#` is a second command
44//! escape character beside `\`, with no name characters: the name of a command
45//! written with `#` is the single character after it, so `#1` is a command named
46//! `1`, `#{` one named `{`, and `##` one named `#`. As for TeX's control symbols,
47//! the space after such a command is kept in the content, so `#1 and` keeps its
48//! space. Each command is looked up through the
49//! providers of the parsing state, innermost first. The template's placeholder
50//! provider ([`PlaceholderProvider`]) returns the placeholder specification for
51//! every command written with the `#` escape and for no other, so `\{` in a
52//! template is never mistaken for a placeholder: the lookup carries the escape
53//! character, and while a techy package cannot tell the two escapes apart, a
54//! provider can.
55//!
56//! Inside the two restricted argument shapes of a template, a characters-only
57//! group (such as the argument of `\ref{…}` or `\label{…}`) and verbatim
58//! content, the same escape stays enabled through the language layer's
59//! restricted-interior policy ([`RestrictedInterior::Template`]). A definition
60//! can therefore pass its argument into a label, a reference target or raw
61//! text. In verbatim content, where groups are not recognized, `#{name}` is
62//! still a placeholder but its name is read as raw characters, and the bracketed
63//! form `#[…]{…}` is not available; in a characters-only group every form is.
64//! Because techy's tokenizer tries commands before special character sequences,
65//! `#` opens a placeholder wherever it is written in a template, so a special
66//! character sequence of the document whose characters begin with `#` cannot be
67//! written inside a template. The template language reserves `#` for itself:
68//! looking for special character sequences first would make the meaning of a
69//! template depend on which sequences happen to be declared.
70//!
71//! # The conditionals
72//!
73//! The eleven conditionals (`\IfNoValueT`, `\IfNoValueF`, `\IfNoValueTF`,
74//! `\IfValueT/F/TF`, `\IfBooleanT/F/TF`, `\ifblank`, `\notblank`), and the
75//! three synonyms of the boolean family with plainer names
76//! (`\IfProvidedT/F/TF`), are ordinary macros of the template language that
77//! carry a [`Conditional`] as the data of their element ([`ElementSpec::value`]);
78//! the expand pass evaluates them at each use and inserts the selected branch. The
79//! fourteen share one element type name ([`CONDITIONAL_ELEMENT`]) and are told
80//! apart by that data: one element type with one element value per command, the way the standard features declare a family of related commands
81//! (see [elements and aspects](crate::guide::concepts_overview#elements-and-aspects)).
82//! [`ConditionalTest`] and [the parent module's documentation](super) describe
83//! what each family tests.
84//!
85//! # What compilation checks
86//!
87//! Every placeholder is resolved against the definition's
88//! [`PlaceholderVocabulary`]: a name an expansion hook computes first, then
89//! `body`, then the named and the numbered arguments. A placeholder that is out
90//! of range, refers to nothing or is misused is reported as
91//! `flm.userdefs.bad-placeholder` when the registry is built, and the definition
92//! is refused; so is any Error diagnostic of the template parse. A template's
93//! errors are therefore found once, when the registry is built, rather than in
94//! each document.
95
96use std::collections::{BTreeMap, BTreeSet};
97use std::fmt;
98use std::sync::Arc;
99
100use techy::core::constructs::{
101    parse_declared_arguments, ConstructParser, ConstructParserResult, Invocation, ParseContext,
102};
103use techy::core::node::{
104    BuildId, CallableData, ContentNodes, NodeBuildError, NodeId, NodeKind, NodeRef, NodeSlice,
105    NodeTree, ParsedArgument, ParsedArguments, ParsedSlots,
106};
107use techy::core::specs::{
108    ArgumentSpec, CallableQuery, CallableSpec, CallableSyntax, Package, ProviderError,
109    SpecsProvider,
110};
111use techy::core::token::{CommandOverrides, CommandRule, TokenEdge, TokenKind, TokenRulesOverrides};
112use techy::core::{DeriveError, FrameRole, ParsingState, ParsingStateDelta};
113use techy::error::{Diagnostic, HookFailed, ParseError, Severity};
114use techy::latexlike::{argument_specs_named, InvocationSyntaxData, Mode};
115use techy::serialize::SerializableObject;
116use techy::source::{Source, SourceSpan, TextContent};
117
118use crate::model::doc::FragmentLayout;
119use crate::model::element::ElementSpec;
120use crate::lang::build::BuiltLang;
121use crate::lang::ext::{TemplateCommandRule, TemplateInteriorRules, RestrictedInterior};
122use crate::lang::flm::{Flm, FlmCallableType};
123use crate::lang::mint::{mint_packages, ArgDef, ArgStdKind, ElementDef, MintError, SyntaxDef};
124use crate::lang::origin::{FlmDiagnostic, FlmOrigin, FlmSource, FlmSpan};
125use crate::lang::parse::{parse_fragment_with_state, ParseOptions};
126use crate::lang::rewrites::userdefs::diagnostics::{
127    BadDefinition, BadPlaceholder, DefinitionProblem, PlaceholderProblem,
128};
129use crate::lang::text::is_space;
130
131/// The escape character that introduces a placeholder in a template: `#`.
132pub const PLACEHOLDER_ESCAPE: char = '#';
133
134/// The placeholder name that refers to an environment's body: `#{body}`.
135pub const BODY_REFERENCE: &str = "body";
136
137/// The name of the template language's techy package (the conditionals), which
138/// is also the owner name of that techy package's element declarations.
139pub const TEMPLATE_PACKAGE_NAME: &str = "_userdefs.template";
140
141/// The name of the placeholder provider ([`PlaceholderProvider`]) among the
142/// providers of a parsing state.
143pub const PLACEHOLDER_PROVIDER_NAME: &str = "_userdefs.placeholder";
144
145/// The element type name of the conditional macros, `flm.userdefs.conditional`;
146/// each conditional is one element value carrying its [`Conditional`].
147pub const CONDITIONAL_ELEMENT: &str = "flm.userdefs.conditional";
148
149// --- the conditionals ---------------------------------------------------------------
150
151/// What a conditional tests about its first argument. There are three different
152/// questions, easy to confuse: *provided* asks whether the use site wrote
153/// something here; *value*, whether there is something to substitute, a
154/// declared default value included; *blank*, whether what would be substituted
155/// is empty or holds only comments.
156///
157/// A declared default value is bound before a conditional is evaluated, which is
158/// why *provided* and *value* are two tests and not one: they differ exactly on
159/// an argument that the use site left out and a default value fills.
160#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
161pub enum ConditionalTest {
162    /// `\IfNoValue…`: the argument is a single placeholder that has nothing to
163    /// substitute: not written at the use site *and* without a declared default
164    /// value.
165    NoValue,
166    /// `\IfValue…`: the negation of [`NoValue`](ConditionalTest::NoValue): the
167    /// placeholder has something to substitute, a declared default value included.
168    Value,
169    /// `\IfBoolean…` and `\IfProvided…`: the argument is a single placeholder whose
170    /// value was written at the use site (typically a `*` marker), or computed by an
171    /// expansion hook. A declared default value does not make this test hold.
172    Boolean,
173    /// `\ifblank`: the argument, with its placeholders substituted, is empty or
174    /// holds nothing but comments. Whitespace is content, and so are groups and
175    /// commands.
176    Blank,
177    /// `\notblank`: the negation of [`Blank`](ConditionalTest::Blank).
178    NotBlank,
179}
180
181/// Which branches a conditional macro takes after its test argument.
182#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
183pub enum Branches {
184    /// One branch, used when the test holds (`…T`).
185    True,
186    /// One branch, used when the test fails (`…F`).
187    False,
188    /// Two branches, the first when the test holds, the second when it fails
189    /// (`…TF`, `\ifblank`, `\notblank`).
190    Both,
191}
192
193/// The data of a conditional macro's element: its test and its branches.
194#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
195pub struct Conditional {
196    /// The test.
197    pub test: ConditionalTest,
198    /// The branches that follow the test argument.
199    pub branches: Branches,
200}
201
202impl Conditional {
203    /// The fourteen conditionals, each with its macro name.
204    pub const ALL: [(&'static str, Conditional); 14] = [
205        ("IfNoValueT", Conditional { test: ConditionalTest::NoValue, branches: Branches::True }),
206        ("IfNoValueF", Conditional { test: ConditionalTest::NoValue, branches: Branches::False }),
207        ("IfNoValueTF", Conditional { test: ConditionalTest::NoValue, branches: Branches::Both }),
208        ("IfValueT", Conditional { test: ConditionalTest::Value, branches: Branches::True }),
209        ("IfValueF", Conditional { test: ConditionalTest::Value, branches: Branches::False }),
210        ("IfValueTF", Conditional { test: ConditionalTest::Value, branches: Branches::Both }),
211        ("IfBooleanT", Conditional { test: ConditionalTest::Boolean, branches: Branches::True }),
212        ("IfBooleanF", Conditional { test: ConditionalTest::Boolean, branches: Branches::False }),
213        ("IfBooleanTF", Conditional { test: ConditionalTest::Boolean, branches: Branches::Both }),
214        ("IfProvidedT", Conditional { test: ConditionalTest::Boolean, branches: Branches::True }),
215        ("IfProvidedF", Conditional { test: ConditionalTest::Boolean, branches: Branches::False }),
216        ("IfProvidedTF", Conditional { test: ConditionalTest::Boolean, branches: Branches::Both }),
217        ("ifblank", Conditional { test: ConditionalTest::Blank, branches: Branches::Both }),
218        ("notblank", Conditional { test: ConditionalTest::NotBlank, branches: Branches::Both }),
219    ];
220
221    /// How many mandatory arguments the macro takes: the test argument plus one
222    /// per branch.
223    pub fn argument_count(&self) -> usize {
224        match self.branches {
225            Branches::True | Branches::False => 2,
226            Branches::Both => 3,
227        }
228    }
229
230    /// The index, in the order the arguments are written, of the branch argument
231    /// selected when the test's outcome is `holds`; `None` when the macro has no
232    /// branch for that outcome.
233    pub fn branch_index(&self, holds: bool) -> Option<usize> {
234        match (self.branches, holds) {
235            (Branches::True, true) | (Branches::False, false) | (Branches::Both, true) => Some(1),
236            (Branches::Both, false) => Some(2),
237            (Branches::True, false) | (Branches::False, true) => None,
238        }
239    }
240}
241
242// --- placeholder references ------------------------------------------------------------
243
244/// What a placeholder refers to, decided when the template is compiled.
245#[derive(Debug, Clone, PartialEq, Eq, Hash)]
246pub enum PlaceholderTarget {
247    /// The argument at this index (in the order the arguments are written, counting
248    /// from zero), for numbered and named placeholders alike, the argument number
249    /// offset applied.
250    Argument(usize),
251    /// The environment's body.
252    Body,
253    /// A name whose content the definition's expansion hook computes.
254    Extra(String),
255}
256
257/// One placeholder of a compiled template.
258#[derive(Debug, Clone, PartialEq, Eq)]
259pub struct PlaceholderRef {
260    /// The placeholder as written between the `#` and the end of the placeholder
261    /// (`1`, `body`, `title`).
262    pub written: String,
263    /// What it refers to.
264    pub target: PlaceholderTarget,
265    /// Whether a substitution argument (`#[…]{…}`) was written; its nodes are the
266    /// placeholder node's first argument, and
267    /// [`CompiledTemplate::substitution_text`] gives their text.
268    pub substitution: bool,
269}
270
271/// The substitution argument of a placeholder node (`#[…]{…}`), when one is
272/// written: the nodes between the brackets.
273pub(crate) fn substitution_of<'t>(node: &NodeRef<'t, Flm>) -> Option<NodeSlice<'t, Flm>> {
274    let provided = node
275        .arguments()
276        .and_then(|arguments| arguments.get(0))
277        .is_some_and(ParsedArgument::is_provided);
278    if provided {
279        node.argument_content_nodes(0)
280    } else {
281        None
282    }
283}
284
285/// The text of a substitution argument's nodes ([`substitution_of`]): their
286/// source text, with the whitespace around it removed; an empty text for an
287/// empty argument (`#[]{name}`). [`ExtraValues`](super::ExtraValues) keys a
288/// value by this text, and [`CompiledTemplate::substitution_text`] gives it for
289/// each placeholder of a template, so that the text a hook reads from a template
290/// is the key the bindings match on.
291pub(crate) fn substitution_text_of(nodes: &NodeSlice<'_, Flm>) -> String {
292    nodes.source_text().map(|text| text.trim().to_string()).unwrap_or_default()
293}
294
295/// A placeholder name whose content a definition's expansion hook computes.
296/// Such names are tried first when a placeholder is resolved; see
297/// [`PlaceholderBindings`](super::PlaceholderBindings).
298#[derive(Debug, Clone, PartialEq, Eq)]
299pub struct ExtraPlaceholder {
300    /// The name, as written between the braces of `#{name}`.
301    pub name: String,
302    /// Whether the name accepts a substitution argument (`#[…]{name}`).
303    pub substitution: bool,
304}
305
306/// What a template may refer to: the declared arguments (by number and, where a
307/// name is declared, by name), the body, and the names whose content an
308/// expansion hook computes. [`Definition::vocabulary`](super::Definition::vocabulary)
309/// builds a user definition's vocabulary.
310#[derive(Debug, Clone, PartialEq, Eq, Default)]
311pub struct PlaceholderVocabulary {
312    /// The number of declared arguments.
313    pub arity: usize,
314    /// The declared name of each argument, by index (`None` for an argument
315    /// declared without a name).
316    pub names: Vec<Option<String>>,
317    /// Whether `#{body}` is available (an environment).
318    pub body: bool,
319    /// The names whose content an expansion hook computes.
320    pub extras: Vec<ExtraPlaceholder>,
321}
322
323impl PlaceholderVocabulary {
324    /// A vocabulary of `arity` arguments without names, with no body and no
325    /// computed names.
326    pub fn new(arity: usize) -> PlaceholderVocabulary {
327        PlaceholderVocabulary { arity, names: vec![None; arity], body: false, extras: Vec::new() }
328    }
329
330    /// Builder: sets the argument names, by index (`None` for an argument without a
331    /// name).
332    pub fn names(mut self, names: Vec<Option<String>>) -> PlaceholderVocabulary {
333        self.names = names;
334        self
335    }
336
337    /// Builder: `#{body}` is available.
338    pub fn with_body(mut self) -> PlaceholderVocabulary {
339        self.body = true;
340        self
341    }
342
343    /// Builder: adds a name whose content an expansion hook computes; it accepts a
344    /// substitution argument when `substitution` is `true`.
345    pub fn extra(mut self, name: impl Into<String>, substitution: bool) -> PlaceholderVocabulary {
346        self.extras.push(ExtraPlaceholder { name: name.into(), substitution });
347        self
348    }
349
350    /// The index of the argument declared with the name `name`, if any.
351    pub fn index_of(&self, name: &str) -> Option<usize> {
352        self.names.iter().position(|declared| declared.as_deref() == Some(name))
353    }
354
355    /// The target of the placeholder written as `written`, with or without a
356    /// substitution argument, under the definition's argument number offset
357    /// `offset`.
358    ///
359    /// The placeholder is resolved in a fixed order: a computed name, then `body`,
360    /// then a declared argument name, then a number. A numbered placeholder `#n`
361    /// refers to the argument at index `n - 1 + offset`; a named placeholder is not
362    /// affected by the offset, which applies only to what is written as a number.
363    ///
364    /// # Errors
365    ///
366    /// The [`PlaceholderProblem`] that says what is wrong with the placeholder: it
367    /// is out of range, refers to nothing, refers to a body the definition does not
368    /// have, or carries a substitution argument where none is accepted.
369    pub fn resolve(
370        &self,
371        written: &str,
372        substitution: bool,
373        offset: usize,
374    ) -> Result<PlaceholderTarget, PlaceholderProblem> {
375        if let Some(extra) = self.extras.iter().find(|extra| extra.name == written) {
376            if substitution && !extra.substitution {
377                return Err(PlaceholderProblem::SubstitutionNotAccepted);
378            }
379            return Ok(PlaceholderTarget::Extra(written.to_string()));
380        }
381        if written == BODY_REFERENCE {
382            if !self.body {
383                return Err(PlaceholderProblem::NoBody);
384            }
385            if substitution {
386                return Err(PlaceholderProblem::SubstitutionNotAccepted);
387            }
388            return Ok(PlaceholderTarget::Body);
389        }
390        if let Some(index) = self.index_of(written) {
391            if substitution {
392                return Err(PlaceholderProblem::SubstitutionNotAccepted);
393            }
394            return Ok(PlaceholderTarget::Argument(index));
395        }
396        if !written.is_empty() && written.bytes().all(|byte| byte.is_ascii_digit()) {
397            // The arity a numbered reference is measured against is what the
398            // offset leaves referable, which is what the diagnostic reports.
399            let referable = self.arity.saturating_sub(offset);
400            let out_of_range = || PlaceholderProblem::OutOfRange { arity: referable };
401            let number: usize = written.parse().map_err(|_| out_of_range())?;
402            if number < 1 || number > referable {
403                return Err(out_of_range());
404            }
405            if substitution {
406                return Err(PlaceholderProblem::SubstitutionNotAccepted);
407            }
408            return Ok(PlaceholderTarget::Argument(number - 1 + offset));
409        }
410        Err(PlaceholderProblem::UnknownName)
411    }
412}
413
414// --- the placeholder spec and its parser -----------------------------------------------
415
416/// Turns a failure to build a node into the error that aborts the parse,
417/// separating a hook failure from an implementation error as techy does (the
418/// language layer's verbatim parsers do the same).
419fn staging_error(
420    cx: &ParseContext<'_, '_, Flm>,
421    error: NodeBuildError,
422    span: FlmSpan,
423) -> ParseError<FlmOrigin> {
424    match error {
425        NodeBuildError::ExtMintFailed { detail } => {
426            ParseError::new(HookFailed::new(detail, None), span)
427        }
428        other => cx.implementation_error(other, span),
429    }
430}
431
432/// The specification of the `#` placeholder command: two declared arguments,
433/// the optional substitution argument `[…]` and the mandatory placeholder name
434/// `{…}` (a single character is read as a braced group, as for any mandatory
435/// argument, which is how `#1` is read). The placeholder's own invocation parser
436/// ([`PlaceholderParser`]) parses them, and also handles the `##` escape and the
437/// raw-name form inside verbatim content.
438pub struct PlaceholderSpec {
439    arguments: Vec<Arc<ArgumentSpec<Flm>>>,
440}
441
442impl PlaceholderSpec {
443    /// The specification.
444    ///
445    /// # Panics
446    ///
447    /// If the argument codes, which are constants of this module, fail to parse.
448    /// No document input can reach this panic.
449    pub fn new() -> PlaceholderSpec {
450        let codes = [("o", "substitution"), ("m", "reference")];
451        let specs = argument_specs_named::<Flm, _, _, _>(codes)
452            .expect("the placeholder argument codes are constants of this module");
453        PlaceholderSpec { arguments: specs }
454    }
455}
456
457impl Default for PlaceholderSpec {
458    fn default() -> PlaceholderSpec {
459        PlaceholderSpec::new()
460    }
461}
462
463impl fmt::Debug for PlaceholderSpec {
464    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
465        f.debug_struct("PlaceholderSpec").finish()
466    }
467}
468
469// The template language is never serialized in build step 1 (a compiled template
470// is a build-time value); the serialization work package may give these types a
471// codec.
472impl SerializableObject<Flm> for PlaceholderSpec {}
473
474impl CallableSpec<Flm> for PlaceholderSpec {
475    fn arguments(&self) -> &[Arc<ArgumentSpec<Flm>>] {
476        &self.arguments
477    }
478
479    fn requires_content(&self) -> bool {
480        true
481    }
482
483    fn make_invocation_parser<'a>(
484        &'a self,
485        invocation: Invocation<'a, Flm>,
486    ) -> Result<Box<dyn ConstructParser<Flm, Output = BuildId> + 'a>, ParseError<FlmOrigin>> {
487        Ok(Box::new(PlaceholderParser { invocation }))
488    }
489
490    fn stack_frame_title(&self, role: FrameRole, name: &str) -> String {
491        match role {
492            FrameRole::Argument { index } => {
493                format!("argument {} of placeholder beginning ‘{}’", index + 1, name)
494            }
495            _ => format!("placeholder beginning ‘{name}’"),
496        }
497    }
498}
499
500/// The change of parsing state under which `#` is an ordinary character: the
501/// command rules without the placeholder escape. The parser reads the escape
502/// again as a character under this state, to place itself right after the `#`
503/// before it parses the bracketed forms.
504fn without_placeholder_escape(state: &ParsingState<Flm>) -> ParsingStateDelta<Flm> {
505    let commands: Vec<Arc<CommandRule>> = state
506        .rules()
507        .command_rules()
508        .iter()
509        .filter(|rule| rule.escape_char != PLACEHOLDER_ESCAPE)
510        .cloned()
511        .collect();
512    ParsingStateDelta::new().rules(TokenRulesOverrides {
513        commands: CommandOverrides { enabled: Some(true), rules: Some(commands) },
514        ..TokenRulesOverrides::default()
515    })
516}
517
518/// The placeholder name of a parsed name argument, read from the nodes already
519/// built: the characters of its content when the content is text, else the
520/// source text the content nodes cover; surrounding whitespace removed.
521fn staged_reference_text(
522    cx: &ParseContext<'_, '_, Flm>,
523    children: &[BuildId],
524    argument: &ParsedArgument<Flm>,
525) -> String {
526    let Some(region) = &argument.region else {
527        return String::new();
528    };
529    let Some((range, content)) = region.staged() else {
530        return String::new();
531    };
532    let staged = cx.staged_nodes();
533    let ids: Vec<BuildId> = match content {
534        ContentNodes::InRegion(inner) => children
535            .get(range.start as usize..range.end as usize)
536            .and_then(|region| region.get(inner.start as usize..inner.end as usize))
537            .map(<[BuildId]>::to_vec)
538            .unwrap_or_default(),
539        ContentNodes::InChildrenOf(parent, inner) => staged
540            .get(*parent)
541            .and_then(|view| view.children().get(inner.start as usize..inner.end as usize))
542            .map(<[BuildId]>::to_vec)
543            .unwrap_or_default(),
544    };
545    let mut text = String::new();
546    let mut all_text = true;
547    for id in &ids {
548        match staged.get(*id) {
549            Some(view) => match view.kind() {
550                NodeKind::Chars { content } => text.push_str(content.resolve(view.span().source())),
551                _ => {
552                    all_text = false;
553                    break;
554                }
555            },
556            None => {
557                all_text = false;
558                break;
559            }
560        }
561    }
562    if !all_text {
563        text.clear();
564        if let (Some(first), Some(last)) = (ids.first(), ids.last()) {
565            if let (Some(first), Some(last)) = (staged.get(*first), staged.get(*last)) {
566                let source = first.span().source();
567                if Arc::ptr_eq(source, last.span().source()) {
568                    let range = first.span().start()..last.span().end();
569                    if let Some(covered) = source.content().get(range) {
570                        text.push_str(covered);
571                    }
572                }
573            }
574        }
575    }
576    text.trim_matches(is_space).to_string()
577}
578
579/// Builds a placeholder node: a command of the placeholder type, named after
580/// the placeholder name, with the given argument records and children (the
581/// regions of the bracketed forms; none for the bare forms), under the current
582/// parsing state.
583fn stage_placeholder(
584    cx: &mut ParseContext<'_, '_, Flm>,
585    invocation: &Invocation<'_, Flm>,
586    reference: &str,
587    arguments: ParsedArguments<Flm>,
588    children: Vec<BuildId>,
589    span: FlmSpan,
590) -> ConstructParserResult<Flm, BuildId> {
591    let data = CallableData {
592        callable_type: FlmCallableType::Placeholder,
593        name: reference.into(),
594        spec: Arc::clone(invocation.spec),
595        arguments,
596        slots: ParsedSlots::empty(),
597        // Recorded as specials syntax although the token was a `#`-escaped
598        // command: a placeholder never survives into a document tree, so its
599        // spelling is never re-emitted (a recomposition of a *template* tree
600        // would print the reference without its `#`; nothing recomposes one).
601        invocation_syntax: InvocationSyntaxData::Specials,
602    };
603    let state = Arc::clone(&cx.state);
604    cx.stage_node(NodeKind::callable(data), span.clone(), state, children)
605        .map_err(|error| staging_error(cx, error, span))
606}
607
608/// The invocation parser of [`PlaceholderSpec`]. The parser's main loop hands it
609/// a command token written with the `#` escape, whose name is the one character
610/// after the escape: a digit is the placeholder name itself; `#` is the escape
611/// for a literal `#`; `{` and `[` start the bracketed forms, read again from the
612/// `#` with the specification's declared arguments (or, inside verbatim content,
613/// as a raw name); any other character is a placeholder name that the compiler
614/// will refuse.
615pub struct PlaceholderParser<'a> {
616    invocation: Invocation<'a, Flm>,
617}
618
619impl PlaceholderParser<'_> {
620    /// `##`: a text node holding one `#`.
621    fn stage_escape(
622        &self,
623        cx: &mut ParseContext<'_, '_, Flm>,
624        span: FlmSpan,
625    ) -> ConstructParserResult<Flm, BuildId> {
626        let kind = NodeKind::chars(TextContent::from(String::from(PLACEHOLDER_ESCAPE)));
627        let state = Arc::clone(&cx.state);
628        cx.stage_node(kind, span.clone(), state, Vec::new())
629            .map_err(|error| staging_error(cx, error, span))
630    }
631
632    /// `#{name}` and `#[…]{name}` where groups are recognized: moves to right after
633    /// the `#` and parses the declared arguments.
634    fn parse_bracketed(
635        &self,
636        cx: &mut ParseContext<'_, '_, Flm>,
637    ) -> ConstructParserResult<Flm, BuildId> {
638        let token = self.invocation.token;
639        cx.tokens.move_to(token, TokenEdge::Start);
640        let plain = cx.derive_state(&without_placeholder_escape(&cx.state))?;
641        let Some(escape) = cx.probe_token(&plain)? else {
642            let here = cx.here();
643            return Err(cx.implementation_error(
644                "the placeholder escape could not be re-read as a character",
645                here,
646            ));
647        };
648        match cx.tokens.token_kind(&escape) {
649            TokenKind::Char(c) if c == PLACEHOLDER_ESCAPE => {}
650            other => {
651                let span = cx.tokens.source_span_of(&escape);
652                return Err(cx.implementation_error(
653                    format!("expected the placeholder escape, found a {} token", other.as_str()),
654                    span,
655                ));
656            }
657        }
658        let start = cx.tokens.position_at(&escape, TokenEdge::Start);
659        let name = cx.tokens.source_span_of(&escape);
660        cx.tokens.move_to(&escape, TokenEdge::EndPastPostSpace);
661        let (children, arguments) = parse_declared_arguments(cx, self.invocation.spec, &name)?;
662        let reference = arguments
663            .get(1)
664            .map(|argument| staged_reference_text(cx, &children, argument))
665            .unwrap_or_default();
666        let end = cx.tokens.position_here();
667        let span = cx.source_span_within(&start, &end)?;
668        stage_placeholder(
669            cx,
670            &self.invocation,
671            &reference,
672            ParsedArguments::from(arguments),
673            children,
674            span,
675        )
676    }
677
678    /// `#{name}` where groups are not recognized (verbatim content): the name is
679    /// read as raw characters up to the closing brace.
680    fn parse_raw_name(
681        &self,
682        cx: &mut ParseContext<'_, '_, Flm>,
683    ) -> ConstructParserResult<Flm, BuildId> {
684        let token = self.invocation.token;
685        let state = Arc::clone(&cx.state);
686        let start = cx.tokens.position_at(token, TokenEdge::Start);
687        let mut name = String::new();
688        let end = loop {
689            let Some(next) = cx.probe_token(&state)? else {
690                break cx.tokens.position_here();
691            };
692            let closes = match cx.tokens.token_kind(&next) {
693                TokenKind::Char('}') => true,
694                TokenKind::GroupClose { delim } => delim == "}",
695                TokenKind::Char(c) => {
696                    name.push(c);
697                    cx.tokens.move_to(&next, TokenEdge::EndPastPostSpace);
698                    continue;
699                }
700                _ => break cx.tokens.position_here(),
701            };
702            if closes {
703                let end = cx.tokens.position_at(&next, TokenEdge::EndPastPostSpace);
704                cx.tokens.move_to(&next, TokenEdge::EndPastPostSpace);
705                break end;
706            }
707            break cx.tokens.position_here();
708        };
709        let span = cx.source_span_within(&start, &end)?;
710        stage_placeholder(
711            cx,
712            &self.invocation,
713            name.trim_matches(is_space),
714            ParsedArguments::empty(),
715            Vec::new(),
716            span,
717        )
718    }
719}
720
721impl fmt::Debug for PlaceholderParser<'_> {
722    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
723        f.debug_struct("PlaceholderParser").field("invocation", &self.invocation).finish()
724    }
725}
726
727impl ConstructParser<Flm> for PlaceholderParser<'_> {
728    type Output = BuildId;
729
730    fn parse(
731        &mut self,
732        cx: &mut ParseContext<'_, '_, Flm>,
733    ) -> ConstructParserResult<Flm, (BuildId, Option<Box<ParsingStateDelta<Flm>>>)> {
734        let token = self.invocation.token;
735        let name: String = match cx.tokens.token_kind(token) {
736            TokenKind::Command { name, .. } => name.to_string(),
737            other => {
738                let span = cx.tokens.source_span_of(token);
739                return Err(cx.implementation_error(
740                    format!("a placeholder was dispatched from a {} token", other.as_str()),
741                    span,
742                ));
743            }
744        };
745        let span = cx.tokens.source_span_of(token);
746        let id = if name.chars().all(|c| c == PLACEHOLDER_ESCAPE) && !name.is_empty() {
747            self.stage_escape(cx, span)?
748        } else if (name == "{" || name == "[") && cx.state.rules().groups_enabled() {
749            self.parse_bracketed(cx)?
750        } else if name == "{" {
751            self.parse_raw_name(cx)?
752        } else {
753            stage_placeholder(
754                cx,
755                &self.invocation,
756                &name,
757                ParsedArguments::empty(),
758                Vec::new(),
759                span,
760            )?
761        };
762        Ok((id, None))
763    }
764}
765
766// --- the placeholder provider ------------------------------------------------------------
767
768// The placeholder is spelled as a command escape rather than as a specials
769// because the restricted-interior policy gates the specials scan as a whole: a
770// specials-shaped placeholder would make every feature's specials visible inside
771// a template's verbatim content, whereas the policy lists command escapes
772// individually.
773
774/// The provider, among those of a parsing state, of the placeholder
775/// specification. It returns the specification for every command written with
776/// the `#` escape (as a macro) and for nothing else, so that the template's own
777/// escape reaches the placeholder parser while the commands written with `\` are
778/// looked up, unchanged, in the packages below it.
779pub struct PlaceholderProvider {
780    spec: Arc<dyn CallableSpec<Flm>>,
781}
782
783impl PlaceholderProvider {
784    /// The provider, over a new [`PlaceholderSpec`].
785    ///
786    /// # Panics
787    ///
788    /// For the same reason as [`PlaceholderSpec::new`]: if the argument codes, which
789    /// are constants of this module, fail to parse. No document input can reach
790    /// this panic.
791    pub fn new() -> PlaceholderProvider {
792        PlaceholderProvider { spec: Arc::new(PlaceholderSpec::new()) }
793    }
794
795    /// The specification that every placeholder node records.
796    pub fn spec(&self) -> &Arc<dyn CallableSpec<Flm>> {
797        &self.spec
798    }
799}
800
801impl Default for PlaceholderProvider {
802    fn default() -> PlaceholderProvider {
803        PlaceholderProvider::new()
804    }
805}
806
807impl fmt::Debug for PlaceholderProvider {
808    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
809        f.debug_struct("PlaceholderProvider").finish()
810    }
811}
812
813impl SerializableObject<Flm> for PlaceholderProvider {}
814
815impl SpecsProvider<Flm> for PlaceholderProvider {
816    fn name(&self) -> &str {
817        PLACEHOLDER_PROVIDER_NAME
818    }
819
820    fn retrieve_spec(
821        &self,
822        query: &CallableQuery<'_, Flm>,
823        _state: &ParsingState<Flm>,
824    ) -> Result<Option<Arc<dyn CallableSpec<Flm>>>, ProviderError> {
825        let placeholder_escape = matches!(
826            query.syntax,
827            CallableSyntax::Command { escape_char } if escape_char == PLACEHOLDER_ESCAPE
828        );
829        if query.callable_type == FlmCallableType::Macro && placeholder_escape {
830            Ok(Some(Arc::clone(&self.spec)))
831        } else {
832            Ok(None)
833        }
834    }
835}
836
837// --- the template language ------------------------------------------------------------
838
839/// The element declarations of the template language's package: the
840/// conditionals, each a macro with mandatory arguments carrying its element,
841/// available in both parsing modes, since a template is read in the mode of
842/// the definition it belongs to.
843fn template_declarations() -> Vec<ElementDef> {
844    let mut defs = Vec::with_capacity(Conditional::ALL.len());
845    for (name, conditional) in Conditional::ALL {
846        let element = Arc::new(
847            ElementSpec::new(CONDITIONAL_ELEMENT)
848                .docs(format!("the conditional `\\{name}` of the template language"))
849                .with_value(Arc::new(conditional)),
850        );
851        let args = vec![ArgDef::new(ArgStdKind::Mandatory); conditional.argument_count()];
852        defs.push(
853            ElementDef::new(TEMPLATE_PACKAGE_NAME, [name], SyntaxDef::Macro { args }, element)
854                .modes([Mode::Text, Mode::Math]),
855        );
856    }
857    defs
858}
859
860/// The template language over a built language: the techy package of the
861/// conditionals, built from their element declarations like every other techy
862/// package a parse uses ([minting](crate::lang::mint)), and the placeholder
863/// provider.
864///
865/// One value serves every template compiled against the same built language: the
866/// `userdefs` feature builds one for all its definitions, and the other features
867/// that compile templates of their own use one in the same way.
868pub struct TemplateLanguage {
869    package: Arc<Package<Flm>>,
870    provider: Arc<PlaceholderProvider>,
871}
872
873impl TemplateLanguage {
874    /// The template language over `lang`: the techy package of the conditionals
875    /// and the placeholder provider.
876    ///
877    /// # Errors
878    ///
879    /// The minting errors of the template language's own declarations. Those
880    /// declarations are constants of this module, so no error is expected; they are
881    /// returned rather than causing a panic, and the compilers report them as
882    /// `flm.userdefs.bad-definition` diagnostics ([`minting_diagnostics`]).
883    pub fn new(lang: &BuiltLang) -> Result<TemplateLanguage, Vec<MintError>> {
884        let defs = template_declarations();
885        let minted = mint_packages(&defs, &[], &[], &[], &BTreeSet::new(), &[], lang.structural());
886        if !minted.errors.is_empty() {
887            return Err(minted.errors);
888        }
889        let Some(package) = minted.packages.into_iter().next() else {
890            return Err(Vec::new());
891        };
892        Ok(TemplateLanguage { package, provider: Arc::new(PlaceholderProvider::new()) })
893    }
894
895    /// The techy package of the conditionals.
896    pub fn package(&self) -> &Arc<Package<Flm>> {
897        &self.package
898    }
899
900    /// The placeholder provider.
901    pub fn provider(&self) -> &Arc<PlaceholderProvider> {
902        &self.provider
903    }
904
905    /// The parsing state in which a template of the parsing mode `mode` is parsed:
906    /// the built language's initial parsing state, with the `#` escape added to the
907    /// command rules, the `Template` restricted-interior policy
908    /// ([`RestrictedInterior::Template`]) keeping that escape enabled inside
909    /// characters-only groups and verbatim content, the two providers (the techy
910    /// package of the conditionals and the placeholder provider) added innermost, and the
911    /// mode set.
912    ///
913    /// # Errors
914    ///
915    /// techy's [`DeriveError`] when the state cannot be derived, for example when a
916    /// provider cannot be added.
917    #[allow(clippy::result_large_err)]
918    pub fn state(
919        &self,
920        lang: &BuiltLang,
921        mode: Mode,
922    ) -> Result<Arc<ParsingState<Flm>>, DeriveError<Flm>> {
923        let base = lang.initial_state();
924        let mut commands: Vec<Arc<CommandRule>> = base.rules().command_rules().to_vec();
925        commands.push(Arc::new(CommandRule {
926            escape_char: PLACEHOLDER_ESCAPE,
927            name_chars: String::new(),
928        }));
929        let rules = TokenRulesOverrides {
930            commands: CommandOverrides { enabled: Some(true), rules: Some(commands) },
931            ..TokenRulesOverrides::default()
932        };
933        let policy = RestrictedInterior::Template(TemplateInteriorRules {
934            commands: vec![TemplateCommandRule {
935                escape_char: PLACEHOLDER_ESCAPE,
936                name_chars: String::new(),
937            }],
938            specials: false,
939        });
940        let ext = lang.initial_state().ext().clone().with_restricted_interior(policy);
941        let package: Arc<dyn SpecsProvider<Flm>> = self.package.clone();
942        let provider: Arc<dyn SpecsProvider<Flm>> = self.provider.clone();
943        let delta = ParsingStateDelta::new()
944            .rules(rules)
945            .ext(ext)
946            .push_provider(package)
947            .push_provider(provider)
948            .mode(mode);
949        lang.derive_state(&delta)
950    }
951}
952
953impl fmt::Debug for TemplateLanguage {
954    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
955        f.debug_struct("TemplateLanguage").field("package", &self.package.name()).finish()
956    }
957}
958
959// --- compilation ------------------------------------------------------------------------
960
961/// What to compile: one template text for one parsing mode, against a
962/// vocabulary, on behalf of a definition. [`compile_template`] and
963/// [`compile_template_with`] take it.
964#[derive(Debug, Clone)]
965pub struct TemplateSpec<'a> {
966    /// The template text.
967    pub text: &'a str,
968    /// The parsing mode the template is compiled for (its nodes are parsed in that
969    /// mode).
970    pub mode: Mode,
971    /// What the template may refer to.
972    pub vocabulary: &'a PlaceholderVocabulary,
973    /// The definition's argument number offset: `#1` is the argument at this
974    /// index (`0` for a definition that declares none).
975    pub offset: usize,
976    /// The definition's name as an author writes it (`\foo`), for diagnostics.
977    pub definition: &'a str,
978    /// The description of the sources created for each use (`expansion of \foo`):
979    /// the label of those sources, through which every expanded node can be traced
980    /// to the expansion.
981    pub label: &'a str,
982    /// What the compiled source is called, without the mode (`template of \foo`,
983    /// `default value of #1 of \foo`). The compiled source's label is this text with
984    /// the mode appended (`template of \foo (text mode)`), so that every diagnostic
985    /// raised while the template is parsed identifies the definition.
986    pub origin_label: &'a str,
987    /// Whether the text is a user definition's own: its template, or the default
988    /// value of one of its arguments. The compiled source's origin is then
989    /// [`FlmOrigin::definition`] rather than [`FlmOrigin::synthetic`], which marks it
990    /// as text that the caller configured for the document.
991    pub user_definition: bool,
992}
993
994/// A template compiled once, to be copied onto a new source at each use: the
995/// text, the source it was parsed from, the tree, and the checked placeholders
996/// by node. Every text node of the tree holds its own text, so a copy of a node
997/// onto another source carries its text with it.
998pub struct CompiledTemplate {
999    text: String,
1000    source: Arc<FlmSource>,
1001    tree: Arc<NodeTree<Flm>>,
1002    mode: Mode,
1003    definition: String,
1004    label: String,
1005    placeholders: BTreeMap<NodeId, PlaceholderRef>,
1006    diagnostics: Vec<FlmDiagnostic>,
1007}
1008
1009impl CompiledTemplate {
1010    /// The template text, which is also the content of every source created for a
1011    /// use.
1012    pub fn text(&self) -> &str {
1013        &self.text
1014    }
1015
1016    /// The source the template was parsed from: every node of
1017    /// [`tree`](CompiledTemplate::tree) has its position in it.
1018    pub fn source(&self) -> &Arc<FlmSource> {
1019        &self.source
1020    }
1021
1022    /// The compiled tree.
1023    pub fn tree(&self) -> &Arc<NodeTree<Flm>> {
1024        &self.tree
1025    }
1026
1027    /// The parsing mode the template was compiled for.
1028    pub fn mode(&self) -> Mode {
1029        self.mode
1030    }
1031
1032    /// The definition's name as an author writes it (`\foo`).
1033    pub fn definition(&self) -> &str {
1034        &self.definition
1035    }
1036
1037    /// The description of the sources created for each use.
1038    pub fn label(&self) -> &str {
1039        &self.label
1040    }
1041
1042    /// The placeholder at `node`, if that node is one.
1043    pub fn placeholder(&self, node: NodeId) -> Option<&PlaceholderRef> {
1044        self.placeholders.get(&node)
1045    }
1046
1047    /// Every placeholder, with its node, in the tree's storage order.
1048    pub fn placeholders(&self) -> impl Iterator<Item = (NodeId, &PlaceholderRef)> + '_ {
1049        self.placeholders.iter().map(|(id, reference)| (*id, reference))
1050    }
1051
1052    /// The text of the substitution argument written on the placeholder at
1053    /// `node` (`#[…]{name}`): the source text between the brackets, with the
1054    /// whitespace around it removed. `#[ \lvert ]{DelimLeft}` gives `\lvert`, and
1055    /// `#[]{DelimLeft}` an empty text. `None` when `node` is not a placeholder of
1056    /// this template, or when the placeholder carries no substitution argument
1057    /// (`#{DelimLeft}`).
1058    ///
1059    /// This text, with the placeholder's name, is the key under which
1060    /// [`ExtraValues`](super::ExtraValues) holds the value of an extra
1061    /// placeholder: an expansion hook lists the placeholders of a template
1062    /// ([`placeholders`](CompiledTemplate::placeholders)) and fills a value for
1063    /// each name and text it finds.
1064    pub fn substitution_text(&self, node: NodeId) -> Option<String> {
1065        if !self.placeholders.contains_key(&node) {
1066            return None;
1067        }
1068        let content = substitution_of(&self.tree.get(node)?)?;
1069        Some(substitution_text_of(&content))
1070    }
1071
1072    /// The diagnostics of the template parse that are not errors.
1073    pub fn diagnostics(&self) -> &[FlmDiagnostic] {
1074        &self.diagnostics
1075    }
1076}
1077
1078impl fmt::Debug for CompiledTemplate {
1079    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1080        f.debug_struct("CompiledTemplate")
1081            .field("text", &self.text)
1082            .field("mode", &self.mode)
1083            .field("definition", &self.definition)
1084            .field("placeholders", &self.placeholders)
1085            .finish()
1086    }
1087}
1088
1089/// The empty position at the start of `source`: where a problem with the
1090/// definition as a whole is reported.
1091fn source_start(source: &Arc<FlmSource>) -> FlmSpan {
1092    SourceSpan::new(source, 0..0)
1093}
1094
1095/// The diagnostics that report a template language that could not be built
1096/// ([`TemplateLanguage::new`]): one `flm.userdefs.bad-definition` per minting
1097/// error, or one when `errors` is empty, each at the start of an empty source
1098/// labeled `declaration of <definition>`, where `definition` is the definition's
1099/// name as an author writes it. A feature that compiles templates of its own
1100/// reports a failure to build the template language with it.
1101pub fn minting_diagnostics(definition: &str, errors: &[MintError]) -> Vec<FlmDiagnostic> {
1102    let origin = FlmOrigin::synthetic(format!("declaration of {definition}"));
1103    let source: Arc<FlmSource> = Arc::new(Source::new(String::new()).with_origin(origin));
1104    let errors = if errors.is_empty() {
1105        vec![String::from("its declarations produced no package and reported no error")]
1106    } else {
1107        errors.iter().map(ToString::to_string).collect()
1108    };
1109    errors
1110        .into_iter()
1111        .map(|detail| {
1112            Diagnostic::error(
1113                BadDefinition::new(definition, DefinitionProblem::Minting { detail }),
1114                source_start(&source),
1115            )
1116        })
1117        .collect()
1118}
1119
1120/// Compiles one template against `lang`, over a template language built for this
1121/// call alone; [`compile_template_with`] shares one template language across
1122/// many templates.
1123///
1124/// On success, the compiled template keeps the diagnostics of the compilation
1125/// that are not errors ([`CompiledTemplate::diagnostics`]).
1126///
1127/// # Errors
1128///
1129/// Every diagnostic of the compilation, when any of them is an Error: the
1130/// template parse's Error diagnostics, the placeholder problems
1131/// (`flm.userdefs.bad-placeholder`), and `flm.userdefs.bad-definition` with the
1132/// problem [`ParseFailed`](super::DefinitionProblem::ParseFailed) when the parse
1133/// returns no tree. The template cannot be used then. When the template language
1134/// cannot be built, the result holds that failure ([`minting_diagnostics`]).
1135pub fn compile_template(
1136    spec: &TemplateSpec<'_>,
1137    lang: &BuiltLang,
1138) -> Result<CompiledTemplate, Vec<FlmDiagnostic>> {
1139    let language = TemplateLanguage::new(lang)
1140        .map_err(|errors| minting_diagnostics(spec.definition, &errors))?;
1141    compile_template_with(spec, lang, &language)
1142}
1143
1144/// The lowercase name of a parsing mode (`text`, `math`), for the label of a
1145/// template's compiled source.
1146fn mode_name(mode: Mode) -> String {
1147    format!("{mode:?}").to_ascii_lowercase()
1148}
1149
1150/// [`compile_template`] over a template language that is already built. The
1151/// compiled source is labeled `<origin_label> (<mode> mode)` and has no
1152/// canonical path, so every diagnostic raised in it identifies the definition;
1153/// its origin marks it as a user definition's text where
1154/// [`TemplateSpec::user_definition`] asks for it.
1155///
1156/// The template is parsed from the template state in its mode
1157/// ([`TemplateLanguage::state`]). The standard state of the parse
1158/// ([`ParseOptions::standard_state`]) is the template state in text mode: an
1159/// argument or a body that declares
1160/// [`FlmEvent::StandardState`](crate::lang::FlmEvent::StandardState) restores
1161/// it, so that a placeholder written there is still a placeholder.
1162///
1163/// # Errors
1164///
1165/// The same as [`compile_template`], except the failure to build the template
1166/// language.
1167pub fn compile_template_with(
1168    spec: &TemplateSpec<'_>,
1169    lang: &BuiltLang,
1170    language: &TemplateLanguage,
1171) -> Result<CompiledTemplate, Vec<FlmDiagnostic>> {
1172    let label = format!("{} ({} mode)", spec.origin_label, mode_name(spec.mode));
1173    let origin =
1174        if spec.user_definition { FlmOrigin::definition(label) } else { FlmOrigin::synthetic(label) };
1175    let source: Arc<FlmSource> = Arc::new(Source::new(spec.text.to_string()).with_origin(origin));
1176    let failed = |detail: String| {
1177        vec![Diagnostic::error(
1178            BadDefinition::new(spec.definition, DefinitionProblem::ParseFailed { detail }),
1179            source_start(&source),
1180        )]
1181    };
1182    let state = language.state(lang, spec.mode).map_err(|error| failed(error.to_string()))?;
1183    // The standard state of the parse is the template state in text mode, so
1184    // that a region that restores the standard state keeps the placeholders.
1185    let standard = match spec.mode {
1186        Mode::Text => Arc::clone(&state),
1187        _ => language.state(lang, Mode::Text).map_err(|error| failed(error.to_string()))?,
1188    };
1189    let options = ParseOptions { standard_state: Some(standard), ..ParseOptions::default() };
1190    // The layout is immaterial: nothing block-related exists at parse (session
1191    // 03 Q2), and only the fragment's tree and diagnostics are kept.
1192    let fragment = parse_fragment_with_state(
1193        lang,
1194        Arc::clone(&source),
1195        FragmentLayout::default(),
1196        &options,
1197        state,
1198    )
1199    .map_err(|error| failed(error.to_string()))?;
1200
1201    let mut diagnostics: Vec<FlmDiagnostic> = fragment.diags().iter().cloned().collect();
1202    // Every text payload owned: a copy onto another source carries its text.
1203    let tree = fragment.tree().materialize();
1204
1205    let mut placeholders = BTreeMap::new();
1206    for node in tree.root().descendants() {
1207        if node.callable_type() != Some(FlmCallableType::Placeholder) {
1208            continue;
1209        }
1210        let written = node.name().unwrap_or("").to_string();
1211        let substitution = node
1212            .arguments()
1213            .and_then(|arguments| arguments.get(0))
1214            .is_some_and(ParsedArgument::is_provided);
1215        match spec.vocabulary.resolve(&written, substitution, spec.offset) {
1216            Ok(target) => {
1217                placeholders.insert(node.id(), PlaceholderRef { written, target, substitution });
1218            }
1219            Err(problem) => diagnostics.push(Diagnostic::error(
1220                BadPlaceholder::new(spec.definition, written, problem),
1221                node.span().clone(),
1222            )),
1223        }
1224    }
1225
1226    if diagnostics.iter().any(|diagnostic| diagnostic.severity() == Severity::Error) {
1227        return Err(diagnostics);
1228    }
1229    Ok(CompiledTemplate {
1230        text: spec.text.to_string(),
1231        source,
1232        tree: Arc::new(tree),
1233        mode: spec.mode,
1234        definition: spec.definition.to_string(),
1235        label: spec.label.to_string(),
1236        placeholders,
1237        diagnostics,
1238    })
1239}
1240
1241/// Compiles one text in each of several parsing modes and keeps it in the modes
1242/// where it compiles: the rule that every text read in more than one mode
1243/// follows.
1244///
1245/// A text is parsed in the mode where it is substituted, so the same text gives
1246/// one compilation per mode, and it may parse in one mode and not in another:
1247/// `\bigl (` parses in a formula and not in running text. The rule: the text is
1248/// kept in each mode where it compiles; a mode where it does not compile is no
1249/// problem of the text, and a use there that needs it is reported at the use;
1250/// only when the text compiles in **none** of `modes` are the failures reported.
1251/// Over a single mode this is simple: the text compiles there, or its failures
1252/// are reported.
1253///
1254/// `compile` performs the compilation in one mode: it returns what the text
1255/// compiled to, or `None` when it did not compile, and pushes the compilation's
1256/// diagnostics onto the vector it is handed (its errors when it fails, its
1257/// warnings when it succeeds).
1258///
1259/// Returns the compilations kept, each with its mode, in the order of `modes`,
1260/// and the diagnostics to report: those of the modes that compiled, or, when
1261/// none did, those of every mode. A user definition's text declared for both
1262/// modes follows this rule ([`compile_with`](super::compile_with)); an extension
1263/// that compiles texts of its own for the modes its templates are read in calls
1264/// this with [`compile_template_with`] as `compile`.
1265pub fn compile_in_modes<T>(
1266    modes: impl IntoIterator<Item = Mode>,
1267    mut compile: impl FnMut(Mode, &mut Vec<FlmDiagnostic>) -> Option<T>,
1268) -> (Vec<(Mode, T)>, Vec<FlmDiagnostic>) {
1269    let mut kept = Vec::new();
1270    let mut kept_diagnostics = Vec::new();
1271    let mut failed_diagnostics = Vec::new();
1272    for mode in modes {
1273        let mut found = Vec::new();
1274        match compile(mode, &mut found) {
1275            Some(compiled) => {
1276                kept.push((mode, compiled));
1277                kept_diagnostics.extend(found);
1278            }
1279            None => failed_diagnostics.extend(found),
1280        }
1281    }
1282    if kept.is_empty() {
1283        (kept, failed_diagnostics)
1284    } else {
1285        (kept, kept_diagnostics)
1286    }
1287}
1288
1289#[cfg(test)]
1290mod tests {
1291    use super::*;
1292
1293    #[test]
1294    fn a_conditional_selects_the_branch_its_test_answers() {
1295        let tf = Conditional { test: ConditionalTest::Value, branches: Branches::Both };
1296        assert_eq!(tf.branch_index(true), Some(1));
1297        assert_eq!(tf.branch_index(false), Some(2));
1298        let t = Conditional { test: ConditionalTest::Value, branches: Branches::True };
1299        assert_eq!(t.branch_index(false), None);
1300        assert_eq!(t.argument_count(), 2);
1301    }
1302
1303    #[test]
1304    fn the_vocabulary_resolves_a_number_under_the_offset() {
1305        let vocabulary = PlaceholderVocabulary::new(3);
1306        assert_eq!(vocabulary.resolve("1", false, 1), Ok(PlaceholderTarget::Argument(1)));
1307        assert_eq!(vocabulary.resolve("2", false, 1), Ok(PlaceholderTarget::Argument(2)));
1308        // The offset shortens the range a number may take, and the diagnostic
1309        // reports what is left referable, not the declared count.
1310        assert_eq!(
1311            vocabulary.resolve("3", false, 1),
1312            Err(PlaceholderProblem::OutOfRange { arity: 2 })
1313        );
1314        assert_eq!(
1315            vocabulary.resolve("0", false, 0),
1316            Err(PlaceholderProblem::OutOfRange { arity: 3 })
1317        );
1318    }
1319
1320    #[test]
1321    fn a_named_reference_ignores_the_offset() {
1322        let vocabulary =
1323            PlaceholderVocabulary::new(2).names(vec![Some(String::from("a")), Some("b".into())]);
1324        assert_eq!(vocabulary.resolve("a", false, 1), Ok(PlaceholderTarget::Argument(0)));
1325        assert_eq!(vocabulary.resolve("1", false, 1), Ok(PlaceholderTarget::Argument(1)));
1326    }
1327
1328    #[test]
1329    fn the_vocabulary_answers_a_hook_name_before_an_argument_name() {
1330        let vocabulary = PlaceholderVocabulary::new(1)
1331            .names(vec![Some(String::from("x"))])
1332            .extra("x", true);
1333        assert_eq!(
1334            vocabulary.resolve("x", true, 0),
1335            Ok(PlaceholderTarget::Extra(String::from("x")))
1336        );
1337    }
1338
1339    #[test]
1340    fn the_vocabulary_refuses_a_substitution_on_a_base_reference() {
1341        let vocabulary = PlaceholderVocabulary::new(1).with_body();
1342        assert_eq!(
1343            vocabulary.resolve("1", true, 0),
1344            Err(PlaceholderProblem::SubstitutionNotAccepted)
1345        );
1346        assert_eq!(
1347            vocabulary.resolve(BODY_REFERENCE, true, 0),
1348            Err(PlaceholderProblem::SubstitutionNotAccepted)
1349        );
1350        assert_eq!(vocabulary.resolve(BODY_REFERENCE, false, 0), Ok(PlaceholderTarget::Body));
1351    }
1352
1353    #[test]
1354    fn the_vocabulary_reports_an_unknown_name_and_a_missing_body() {
1355        let vocabulary = PlaceholderVocabulary::new(0);
1356        assert_eq!(vocabulary.resolve("nope", false, 0), Err(PlaceholderProblem::UnknownName));
1357        assert_eq!(vocabulary.resolve(BODY_REFERENCE, false, 0), Err(PlaceholderProblem::NoBody));
1358    }
1359}