Skip to main content

flm_core/lang/
copy.rs

1//! Building a synthesized value from nodes of an existing tree:
2//! [`copy_run_into_value`] and [`copy_pieces_into_value`].
3//!
4//! A synthesized value is a small tree that a stage builds while a run is under
5//! way, held outside the document's trees (see [synthesized
6//! values](crate::guide::concepts_overview#synthesized-values)). Examples are
7//! the content a `\ref` displays, a formatted citation entry, and the exact
8//! source text an emitter has to print back. A synthesized value (a *value*
9//! for short in this module) is lowered and rendered like document content,
10//! but no stage that scans the document reads it.
11//!
12//! This module copies nodes *out of* a tree into a new value. Copying nodes
13//! *into* a tree being built, as a lowering rule does when it adds a copy to
14//! the presentation tree, belongs to the lowering driver and does not use this
15//! module.
16//!
17//! # Copying a run of nodes
18//!
19//! [`copy_run_into_value`] builds a value from a run of sibling nodes of an
20//! existing tree. Every copied node keeps its own span and its own source, so a
21//! diagnostic raised about the value still points at the place in the document
22//! where the content was written. The copies are the children of a new list
23//! node (a container node, element
24//! [`flm.container`](crate::lang::structural::CONTAINER)) spanning the run,
25//! which is the value's root.
26//!
27//! # Copying value pieces
28//!
29//! [`copy_pieces_into_value`] builds a value from a list of value pieces
30//! ([`ValuePiece`]), each of one of four kinds:
31//!
32//! - a node, copied with its subtree;
33//! - characters that are not a node of their own, which become a new text
34//!   node. An example is the value `Custom` of `tag=Custom`, which shares its
35//!   text node with the key. [`key_value_pieces`] reads the value of a
36//!   key-value entry into such pieces ([`WrittenPiece`]);
37//! - a new node of a synthesized element around further pieces
38//!   ([`SynthesizedPiece`]), for content that needs a structure of its own. Such
39//!   a node may carry data of its own (a [payload](crate::lang::PresPayload))
40//!   and may hold no piece at all. For example, an
41//!   [xnote](crate::stdlib::features::xnotes) is a note set apart from the
42//!   running text and shown elsewhere or in place (a footnote, an endnote, a
43//!   side note); the list of an xnote kind is made of such nodes, each entry
44//!   holding a node whose payload refers to the xnote whose content it shows,
45//!   instead of a copy of that content;
46//! - a new node of a command of the language around further pieces
47//!   ([`CommandPiece`]), for content that needs a command such as emphasis or
48//!   a link. The node is the one a parse of the command would produce, so it
49//!   is read and lowered like the written command.
50//!
51//! # Content shown again and content of the value's own
52//!
53//! Every copy is made for a purpose ([`ValueContent`]): to show content of the
54//! document a second time, away from where it is written (what a reference
55//! shows of the heading it refers to), or to hold content as the value's own.
56//!
57//! - A copy of the value's own ([`ValueContent::Own`]) copies every node as it
58//!   is.
59//! - A copy shown again ([`ValueContent::Shown`]) asks each node it copies, at
60//!   every depth, what to put in its place: the element's
61//!   [`InCopy`](crate::model::aspects::InCopy) aspect, read through
62//!   [`copied_as`]. The aspect returns the node itself over the copies of its
63//!   children (the default, for every element without the aspect), nothing, or
64//!   one new node of the element's own, at the node's span and without
65//!   children. An xnote, for example, is replaced by such a node, which the
66//!   xnote's lowering rules write as the xnote's mark: a note shown again is
67//!   not a second note.
68//!
69//! # Copies must run on a worker thread
70//!
71//! The copy is a guarded traversal ([`crate::lang::guard`]) that does not check
72//! its thread: call these functions on a worker thread, for example inside
73//! [`on_worker_thread`](crate::lang::guard::on_worker_thread).
74
75use std::sync::Arc;
76
77use techy::core::node::{
78    BodySlotExt, BuildId, CallableData, ChildRegion, ContentNodes, NodeKind, NodeRef, NodeSlice,
79    NodeTree, ParsedArgument, ParsedArguments, ParsedSlot, ParsedSlots, SlotRole,
80};
81use techy::core::specs::{CallableQuery, CallableSpec, CallableSyntax};
82use techy::core::{Lang, ParsingState};
83use techy::latexlike::{BodyMarker, InvocationSyntaxData};
84use techy::source::{SourceSpan, TextContent};
85use techy::transform::{Restage, RestageContext, RestageError, RestageVisitor};
86
87use crate::lang::guard::{self, GuardPolicy};
88use crate::lang::mint::specs::element_of_spec;
89use crate::lang::mint::FlmSynthesizedSpec;
90use crate::lang::structural::UNKNOWN_MACRO;
91use crate::lang::text::{is_blank, is_blank_text, is_space};
92use crate::lang::{Flm, FlmCallableType, FlmSpan, PresPayload};
93use crate::model::aspects::{CopiedAs, copied_as};
94
95/// The reasons a run of nodes or a list of value pieces ([`ValuePiece`]) could
96/// not be copied into a value.
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub enum CopyError {
99    /// The [recursion guard](crate::lang::guard) refused to descend further: the
100    /// content is nested too deeply.
101    NestingTooDeep {
102        /// techy's description of the limit that was reached.
103        detail: String,
104    },
105    /// Building the copy failed for another reason. This is an error in the
106    /// program (for example, the nodes passed to [`copy_run_into_value`] did
107    /// not belong to the tree of its `anchor` argument, or a node extension
108    /// could not be built), not something a document causes.
109    Failed {
110        /// techy's description of what failed.
111        detail: String,
112    },
113}
114
115impl std::fmt::Display for CopyError {
116    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117        match self {
118            CopyError::NestingTooDeep { detail } => {
119                write!(f, "the content nests too deeply to copy: {detail}")
120            }
121            CopyError::Failed { detail } => write!(f, "copying the content failed: {detail}"),
122        }
123    }
124}
125
126impl std::error::Error for CopyError {}
127
128impl From<RestageError<CopyError>> for CopyError {
129    fn from(error: RestageError<CopyError>) -> CopyError {
130        match error {
131            RestageError::Visitor(error) => error,
132            RestageError::DescentLimitExceeded { detail, .. } => CopyError::NestingTooDeep { detail },
133            other => CopyError::Failed { detail: other.to_string() },
134        }
135    }
136}
137
138/// A visitor that copies every node unchanged: the copy of the value's own
139/// ([`ValueContent::Own`]).
140struct Verbatim;
141
142impl RestageVisitor<Flm, (), ()> for Verbatim {
143    type Error = CopyError;
144
145    fn restage(
146        &mut self,
147        _node: NodeRef<'_, Flm>,
148        _cx: &mut RestageContext<'_, Flm, (), ()>,
149    ) -> Result<Restage<()>, CopyError> {
150        Ok(Restage::Descend(()))
151    }
152}
153
154/// A visitor for a copy shown again ([`ValueContent::Shown`]): it asks each
155/// node's element what to put in the node's place ([`copied_as`]) and adds
156/// that to the copy: the node over the copies of its children, nothing, or one
157/// new node of the element's own, at the node's span and under its parsing
158/// state, without children.
159struct AskEach;
160
161impl RestageVisitor<Flm, (), ()> for AskEach {
162    type Error = CopyError;
163
164    fn restage(
165        &mut self,
166        node: NodeRef<'_, Flm>,
167        cx: &mut RestageContext<'_, Flm, (), ()>,
168    ) -> Result<Restage<()>, CopyError> {
169        match copied_as(&node, ValueContent::Shown) {
170            CopiedAs::Verbatim => Ok(Restage::Descend(())),
171            CopiedAs::Nothing => Ok(Restage::Emit(Vec::new())),
172            CopiedAs::StandIn(stand_in) => {
173                let kind = NodeKind::callable(stand_in.spec.callable_data());
174                let span = node.span().clone();
175                let state = Arc::clone(node.parsing_state());
176                let staged = stage_node_with(cx, kind, span, state, Vec::new(), stand_in.payload)?;
177                Ok(Restage::Emit(vec![staged]))
178            }
179        }
180    }
181}
182
183/// The purpose of a copy: whether the copied content shows document content a
184/// second time or belongs to the value. The code that builds the value passes it
185/// to [`copy_run_into_value`] or [`copy_pieces_into_value`].
186///
187/// The purpose decides how each node is copied: a copy of the value's own
188/// copies every node as it is, and a copy shown again asks each node's element
189/// what to put in its place ([`copied_as`]); see the [module
190/// documentation](self#content-shown-again-and-content-of-the-values-own).
191///
192/// The purpose affects the copy only: the value records nothing of it, and
193/// every diagnostic its content raises when the value is brought up to date
194/// and lowered is reported, regardless of the purpose.
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub enum ValueContent {
197    /// Content of the document shown a second time, away from where it is
198    /// written: what a reference shows of the point it refers to (a heading's
199    /// title, a list item's tag, the alternative text of a float's caption).
200    /// Each node is copied as its element's
201    /// [`InCopy`](crate::model::aspects::InCopy) aspect says.
202    Shown,
203    /// Content the value holds as its own: a structure the value builds
204    /// around content lowered nowhere else (the list of an
205    /// [xnote](crate::stdlib::features::xnotes) kind, the
206    /// lead-in of a term definition), the use site of a user definition copied
207    /// to be expanded in place, or content copied only to be read. Every node
208    /// is copied as it is, regardless of what its element would put in its
209    /// place for a copy shown again, because a use site copied to be expanded
210    /// in place *is* the document's content there, and content copied to be
211    /// read must be what was written.
212    Own,
213}
214
215/// One value piece: a part of the content [`copy_pieces_into_value`] copies: a
216/// node, copied with its subtree; characters that are not a node of their own;
217/// or a new node of a synthesized element or of a command, holding pieces of
218/// its own.
219#[derive(Debug, Clone, Copy)]
220pub enum ValuePiece<'n, 't> {
221    /// A node of any tree, copied with its subtree as the copy's purpose says
222    /// ([`ValueContent`]).
223    Node(NodeRef<'t, Flm>),
224    /// Characters, added as one new text node with an empty span at the
225    /// anchor's start (or at the start of the enclosing piece's span).
226    Text(&'n str),
227    /// A new node of a synthesized element, holding the copy of its own pieces
228    /// ([`SynthesizedPiece`]).
229    Synthesized(&'n SynthesizedPiece<'n, 't>),
230    /// A new node of a command of the language, whose arguments hold the
231    /// copies of pieces ([`CommandPiece`]).
232    Command(&'n CommandPiece<'n, 't>),
233}
234
235/// A new node that [`copy_pieces_into_value`] creates around value pieces
236/// ([`ValuePiece`]): a node of a [synthesized
237/// element](crate::lang::mint::SyntaxDef::Synthesized) (an element no document
238/// writes) with one content slot, which holds the copy of `body`.
239///
240/// `body` is copied like any other pieces, except that a text piece in it gets
241/// an empty span at the start of `span` instead of at the anchor's start. The
242/// node carries `payload`, when there is one, as its own data
243/// ([`FlmNodeExt::payload`](crate::lang::FlmNodeExt::payload)).
244///
245/// This is how a value gets a structure of its own. For example, the list of an
246/// [xnote](crate::stdlib::features::xnotes) kind (a kind of footnote, endnote
247/// or side note) is one list node holding one entry node per xnote, each
248/// holding a node whose payload refers to the xnote whose content the entry
249/// shows.
250#[derive(Clone)]
251pub struct SynthesizedPiece<'n, 't> {
252    /// The specification of the node, which carries its synthesized element.
253    pub spec: Arc<FlmSynthesizedSpec>,
254    /// The name of the node's content slot, which holds the copy of `body`.
255    pub slot: &'n str,
256    /// The node's span: where a diagnostic about the node points.
257    pub span: FlmSpan,
258    /// The parsing state the node is added under.
259    pub state: Arc<ParsingState<Flm>>,
260    /// The pieces the node holds, in order.
261    pub body: Vec<ValuePiece<'n, 't>>,
262    /// The node's own data, set in its extension; `None` for a node that
263    /// carries none.
264    pub payload: Option<Arc<dyn PresPayload>>,
265}
266
267impl std::fmt::Debug for SynthesizedPiece<'_, '_> {
268    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
269        f.debug_struct("SynthesizedPiece")
270            .field("element", &self.spec.element().name)
271            .field("slot", &self.slot)
272            .field("span", &self.span)
273            .field("body", &self.body)
274            .finish_non_exhaustive()
275    }
276}
277
278/// A new node that [`copy_pieces_into_value`] creates for a command of the
279/// language (`\emph{…}`, `\href{…}{…}`) whose arguments hold value pieces
280/// ([`ValuePiece`]): the node a parse of the command written with those
281/// arguments would produce, carrying the command's element, so that it is read,
282/// rewritten and lowered like the written command.
283///
284/// Build one with [`CommandPiece::new`], which looks the command up in the
285/// language as a parsing state defines it, then fill
286/// [`arguments`](CommandPiece::arguments). The node is recorded as written with
287/// a backslash and nothing after the name. Each provided argument's content is
288/// the copies of its pieces, as direct children of the node; a text piece gets
289/// an empty span at the start of the node's span.
290#[derive(Clone)]
291pub struct CommandPiece<'n, 't> {
292    /// The command's name without its backslash: `emph`.
293    name: String,
294    /// The command's specification in the language.
295    spec: Arc<dyn CallableSpec<Flm>>,
296    /// The node's span: where a diagnostic about the node points.
297    pub span: FlmSpan,
298    /// The parsing state the node is added under, and in which the command
299    /// was looked up.
300    pub state: Arc<ParsingState<Flm>>,
301    /// The pieces of each argument, in the order in which the command declares
302    /// its arguments; `None`, or no entry past the end of the list, for an
303    /// argument not provided. More entries than the command has arguments make
304    /// the copy fail ([`CopyError::Failed`]).
305    pub arguments: Vec<Option<Vec<ValuePiece<'n, 't>>>>,
306}
307
308impl<'n, 't> CommandPiece<'n, 't> {
309    /// Returns the command `\name` as the language defines it under `state`,
310    /// at `span`, with no argument provided yet: `Ok(Some(_))` for a command
311    /// the language defines there; `Ok(None)` where it defines no such command
312    /// (the feature that defines it is not in the registry, and a parse would
313    /// treat the command as unknown, [`UNKNOWN_MACRO`]).
314    ///
315    /// # Errors
316    ///
317    /// [`CopyError::Failed`] when looking the command up fails: a provider of
318    /// command definitions on the state's scope stack returned an error.
319    pub fn new(name: &str, span: FlmSpan, state: Arc<ParsingState<Flm>>) -> Result<Option<CommandPiece<'n, 't>>, CopyError> {
320        let query = CallableQuery::new(FlmCallableType::Macro, name, CallableSyntax::Command { escape_char: '\\' });
321        // A source of command definitions that cannot answer is a failure,
322        // never a command the language does not define.
323        let spec = match state.scopes().retrieve_spec(&query, &state) {
324            Ok(Some(spec)) => spec,
325            Ok(None) => return Ok(None),
326            Err(error) => {
327                return Err(CopyError::Failed { detail: format!("looking up the command `\\{name}` failed: {error}") })
328            }
329        };
330        match element_of_spec(&*spec) {
331            Some(element) if element.name.as_str() != UNKNOWN_MACRO => {
332                Ok(Some(CommandPiece { name: name.to_string(), spec, span, state, arguments: Vec::new() }))
333            }
334            _ => Ok(None),
335        }
336    }
337
338    /// Returns the command's name without its backslash.
339    pub fn name(&self) -> &str {
340        &self.name
341    }
342}
343
344impl std::fmt::Debug for CommandPiece<'_, '_> {
345    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
346        f.debug_struct("CommandPiece")
347            .field("name", &self.name)
348            .field("span", &self.span)
349            .field("arguments", &self.arguments)
350            .finish_non_exhaustive()
351    }
352}
353
354/// One piece of the value of a key-value entry, as the author wrote it in a
355/// bracket: a node of the document, or characters split off a text node that
356/// also holds the key (`Custom` in `tag=Custom`), which are not a node of their
357/// own.
358///
359/// [`key_value_pieces`] returns the value of an entry as such pieces; examples
360/// are the tag of an `\item`, a list's own label, the alternative text of a
361/// float's `\caption`. Unlike a [`ValuePiece`], it owns its characters, so a
362/// reader can pass it on; a copy takes each piece as a [`ValuePiece`]
363/// ([`WrittenPiece::as_value_piece`]).
364#[derive(Debug, Clone)]
365pub enum WrittenPiece<'t> {
366    /// A node of the tree that holds the bracket, shown as the content it is.
367    Node(NodeRef<'t, Flm>),
368    /// Characters of the document, as the tree holds them.
369    Text(String),
370}
371
372impl<'t> WrittenPiece<'t> {
373    /// Returns the piece as [`copy_pieces_into_value`] takes it: the node, or
374    /// the characters.
375    pub fn as_value_piece(&self) -> ValuePiece<'_, 't> {
376        match self {
377            WrittenPiece::Node(node) => ValuePiece::Node(*node),
378            WrittenPiece::Text(text) => ValuePiece::Text(text),
379        }
380    }
381}
382
383/// Returns the value of a key-value entry as value pieces ([`ValuePiece`]) of
384/// document content: `value` is the entry's value as techy's key-value reader
385/// read it from the bracket whose content is `content`.
386///
387/// The key-value reader builds a tree of its own, whose nodes carry the spans
388/// they were read from. A group or a callable of the value is returned as the
389/// node of the document it was read from, found in `content` by its span;
390/// characters split off a text node that also holds the key are returned as
391/// text. Whitespace at either end is dropped, a node that is whitespace (such
392/// as `~`) included.
393///
394/// The features whose brackets hold such values (lists, floats) all read them
395/// through this function.
396pub fn key_value_pieces<'t>(
397    content: &NodeSlice<'t, Flm>,
398    value: NodeSlice<'_, Flm>,
399) -> Vec<WrittenPiece<'t>> {
400    let pieces: Vec<WrittenPiece<'t>> = value
401        .iter()
402        .map(|piece| {
403            let found = whole_node(content, &piece);
404            match (found, piece.chars()) {
405                (Some(node), _) => WrittenPiece::Node(node),
406                (None, Some(text)) => WrittenPiece::Text(text.to_string()),
407                // A derived node that is not characters always stands for a
408                // whole node of the bracket; nothing else can be answered.
409                (None, None) => WrittenPiece::Text(String::new()),
410            }
411        })
412        .collect();
413    trim_pieces(pieces)
414}
415
416/// Returns `pieces` (value pieces, [`ValuePiece`]) with the whitespace at
417/// either end dropped: the blank pieces at each end (text holding only
418/// whitespace, [`is_blank_text`], and a blank node, [`is_blank`]: a text node
419/// holding only whitespace, or a node that is whitespace, such as `~` and
420/// `\ `), and the whitespace ([`is_space`]) a text piece at either end begins
421/// or ends with.
422pub(crate) fn trim_pieces(mut pieces: Vec<WrittenPiece<'_>>) -> Vec<WrittenPiece<'_>> {
423    let blank = |piece: &WrittenPiece<'_>| match piece {
424        WrittenPiece::Text(text) => is_blank_text(text),
425        WrittenPiece::Node(node) => is_blank(node),
426    };
427    while pieces.first().is_some_and(blank) {
428        pieces.remove(0);
429    }
430    while pieces.last().is_some_and(blank) {
431        pieces.pop();
432    }
433    if let Some(WrittenPiece::Text(text)) = pieces.first_mut() {
434        *text = text.trim_start_matches(is_space).to_string();
435    }
436    if let Some(WrittenPiece::Text(text)) = pieces.last_mut() {
437        *text = text.trim_end_matches(is_space).to_string();
438    }
439    pieces
440}
441
442/// Returns the node of the bracket `content` that `piece`, a node of the
443/// key-value reader's own tree, was read from as a whole, if there is one.
444///
445/// The reader's nodes carry the spans they were read from: a group or a
446/// callable of a value is a whole node of the document, found by its span. A
447/// text node split at the key keeps, where the block-structure pass rewrote
448/// it, the span of the whole text node, key included, so characters are
449/// matched to a node only when they are also that node's characters.
450fn whole_node<'t>(
451    content: &NodeSlice<'t, Flm>,
452    piece: &NodeRef<'_, Flm>,
453) -> Option<NodeRef<'t, Flm>> {
454    content.iter().find(|node| {
455        node.span().start() == piece.span().start()
456            && node.span().end() == piece.span().end()
457            && node.chars() == piece.chars()
458    })
459}
460
461/// The visitor that produces the value. It is called once, at the tree's root,
462/// and returns a new list node holding the copies of the pieces; nothing else
463/// is visited.
464struct CopyRun<'n, 't> {
465    pieces: &'n [ValuePiece<'n, 't>],
466    anchor: NodeRef<'t, Flm>,
467    content: ValueContent,
468}
469
470impl RestageVisitor<Flm, (), ()> for CopyRun<'_, '_> {
471    type Error = CopyError;
472
473    fn restage(
474        &mut self,
475        _root: NodeRef<'_, Flm>,
476        cx: &mut RestageContext<'_, Flm, (), ()>,
477    ) -> Result<Restage<()>, CopyError> {
478        let at = self.anchor.span();
479        let text_at = SourceSpan::new(at.source(), at.start()..at.start());
480        let children = stage_pieces(cx, self.pieces, self.content, &text_at, self.anchor.parsing_state())?;
481        let (span, state) = where_pieces_stand(self.pieces).unwrap_or_else(|| {
482            let at = self.anchor.span();
483            (
484                SourceSpan::new(at.source(), at.start()..at.start()),
485                Arc::clone(self.anchor.parsing_state()),
486            )
487        });
488        let root = stage_node(cx, NodeKind::list(), span, state, children)?;
489        Ok(Restage::Emit(vec![root]))
490    }
491}
492
493/// Adds the copy of each of `pieces`, in order: a node with its subtree, as
494/// `purpose` says (unchanged for a copy of the value's own, as each element
495/// says for a copy shown again, [`AskEach`]); a text as a new text node at the
496/// empty span `text_at` under `text_state`; a synthesized or command piece as a
497/// new node holding the copy of its own pieces, made the same way, whose texts
498/// get the empty span at the piece's own start.
499fn stage_pieces(
500    cx: &mut RestageContext<'_, Flm, (), ()>,
501    pieces: &[ValuePiece<'_, '_>],
502    purpose: ValueContent,
503    text_at: &FlmSpan,
504    text_state: &Arc<ParsingState<Flm>>,
505) -> Result<Vec<BuildId>, CopyError> {
506    let failed = |error: &dyn std::fmt::Display| CopyError::Failed { detail: error.to_string() };
507    let mut children = Vec::with_capacity(pieces.len());
508    for piece in pieces {
509        match piece {
510            ValuePiece::Node(node) => {
511                let copied = match purpose {
512                    ValueContent::Own => cx.restage_subtree(*node, &mut Verbatim)?,
513                    ValueContent::Shown => cx.restage_subtree(*node, &mut AskEach)?,
514                };
515                children.extend(copied);
516            }
517            ValuePiece::Text(text) => {
518                let kind = NodeKind::chars(TextContent::Owned(Box::from(*text)));
519                let state = Arc::clone(text_state);
520                children.push(stage_node(cx, kind, text_at.clone(), state, Vec::new())?);
521            }
522            ValuePiece::Synthesized(piece) => {
523                let start = SourceSpan::new(piece.span.source(), piece.span.start()..piece.span.start());
524                let body = stage_pieces(cx, &piece.body, purpose, &start, &piece.state)?;
525                let count = u32::try_from(body.len()).map_err(|error| failed(&error))?;
526                let mut data = piece.spec.callable_data();
527                data.slots = ParsedSlots::new(vec![ParsedSlot::new(
528                    ChildRegion::new(0..count, ContentNodes::InRegion(0..count)),
529                    piece.slot,
530                    SlotRole::Content,
531                    BodyMarker::make_body(),
532                )]);
533                let kind = NodeKind::callable(data);
534                let state = Arc::clone(&piece.state);
535                let payload = piece.payload.clone();
536                children.push(stage_node_with(cx, kind, piece.span.clone(), state, body, payload)?);
537            }
538            ValuePiece::Command(piece) => children.push(stage_command(cx, piece, purpose)?),
539        }
540    }
541    Ok(children)
542}
543
544/// Adds the new node of a command piece, each provided argument holding the
545/// copies of its pieces.
546fn stage_command(
547    cx: &mut RestageContext<'_, Flm, (), ()>,
548    piece: &CommandPiece<'_, '_>,
549    purpose: ValueContent,
550) -> Result<BuildId, CopyError> {
551    let failed = |detail: String| CopyError::Failed { detail };
552    let specs = piece.spec.arguments();
553    if piece.arguments.len() > specs.len() {
554        return Err(failed(format!(
555            "`\\{}` takes {} {}, not {}",
556            piece.name,
557            specs.len(),
558            if specs.len() == 1 { "argument" } else { "arguments" },
559            piece.arguments.len()
560        )));
561    }
562    let start = SourceSpan::new(piece.span.source(), piece.span.start()..piece.span.start());
563    let mut children: Vec<BuildId> = Vec::new();
564    let mut arguments = Vec::with_capacity(specs.len());
565    for (index, spec) in specs.iter().enumerate() {
566        let Some(Some(pieces)) = piece.arguments.get(index) else {
567            arguments.push(ParsedArgument::absent(Arc::clone(spec)));
568            continue;
569        };
570        let staged = stage_pieces(cx, pieces, purpose, &start, &piece.state)?;
571        let from = u32::try_from(children.len()).map_err(|error| failed(error.to_string()))?;
572        let count = u32::try_from(staged.len()).map_err(|error| failed(error.to_string()))?;
573        children.extend(staged);
574        let region = ChildRegion::new(from..from + count, ContentNodes::InRegion(0..count));
575        arguments.push(ParsedArgument::provided(Arc::clone(spec), region, ()));
576    }
577    let kind = NodeKind::callable(CallableData {
578        callable_type: FlmCallableType::Macro,
579        name: Box::from(piece.name.as_str()),
580        spec: Arc::clone(&piece.spec),
581        arguments: ParsedArguments::new(arguments),
582        slots: ParsedSlots::empty(),
583        invocation_syntax: InvocationSyntaxData::Macro {
584            escape_char: '\\',
585            post_space: TextContent::Owned(Box::from("")),
586        },
587    });
588    stage_node(cx, kind, piece.span.clone(), Arc::clone(&piece.state), children)
589}
590
591/// Adds one new node of `kind` over the already added `children`.
592fn stage_node(
593    cx: &mut RestageContext<'_, Flm, (), ()>,
594    kind: NodeKind<Flm>,
595    span: FlmSpan,
596    state: Arc<ParsingState<Flm>>,
597    children: Vec<BuildId>,
598) -> Result<BuildId, CopyError> {
599    stage_node_with(cx, kind, span, state, children, None)
600}
601
602/// Adds one new node of `kind` over the already added `children`, carrying
603/// `payload` when there is one.
604fn stage_node_with(
605    cx: &mut RestageContext<'_, Flm, (), ()>,
606    kind: NodeKind<Flm>,
607    span: FlmSpan,
608    state: Arc<ParsingState<Flm>>,
609    children: Vec<BuildId>,
610    payload: Option<Arc<dyn PresPayload>>,
611) -> Result<BuildId, CopyError> {
612    let failed = |error: &dyn std::fmt::Display| CopyError::Failed { detail: error.to_string() };
613    let mut ext = Flm::make_node_ext(&kind, &span, &state, cx.builder().staged_children(&children))
614        .map_err(|error| failed(&error))?;
615    if let Some(payload) = payload {
616        ext = ext.with_payload(payload);
617    }
618    cx.builder().add(kind, span, state, children, ext, ()).map_err(|error| failed(&error))
619}
620
621/// Returns the span covering the pieces that have a place in a source (the
622/// nodes, the synthesized pieces and the command pieces, from the first to the
623/// last) and the parsing state of the first; `None` when there is none.
624fn where_pieces_stand(pieces: &[ValuePiece<'_, '_>]) -> Option<(FlmSpan, Arc<ParsingState<Flm>>)> {
625    let located = |piece: &ValuePiece<'_, '_>| match piece {
626        ValuePiece::Node(node) => Some((node.span().clone(), Arc::clone(node.parsing_state()))),
627        ValuePiece::Synthesized(piece) => Some((piece.span.clone(), Arc::clone(&piece.state))),
628        ValuePiece::Command(piece) => Some((piece.span.clone(), Arc::clone(&piece.state))),
629        ValuePiece::Text(_) => None,
630    };
631    let (first, state) = pieces.iter().find_map(located)?;
632    let (last, _) = pieces.iter().rev().find_map(located)?;
633    Some((covering(&first, &last), state))
634}
635
636/// Returns the span covering a run from `first` to `last`, or `first` alone
637/// when the two are in different sources or in reverse order.
638fn covering(first: &FlmSpan, last: &FlmSpan) -> FlmSpan {
639    if first.same_source(last) && first.start() <= last.end() {
640        SourceSpan::new(first.source(), first.start()..last.end())
641    } else {
642        first.clone()
643    }
644}
645
646/// Copies `nodes` into a new value tree and returns it: a list node, spanning
647/// the whole run, holding a copy of each node. This is
648/// [`copy_pieces_into_value`] with every piece a node.
649///
650/// `nodes` must be nodes of `anchor`'s tree. `anchor` also supplies the span
651/// and the parsing state when `nodes` is empty: the root then gets an empty
652/// span at `anchor`'s start. Each copy keeps the span, source and parsing state
653/// of the node it was made from. `content` is the purpose of the copy
654/// ([`ValueContent`]), which decides whether each node is copied unchanged or
655/// as its element says.
656///
657/// The traversal runs under the recursion guard of `guard` and does not check
658/// its thread: call this function on a worker thread
659/// ([`on_worker_thread`](crate::lang::guard::on_worker_thread)), as the example
660/// does.
661///
662/// # Errors
663///
664/// [`CopyError::NestingTooDeep`] when the content is nested deeper than `guard`
665/// allows; [`CopyError::Failed`] when building the copy fails, which means the
666/// arguments did not meet this function's requirements.
667///
668/// # Examples
669///
670/// The copy is guarded, so the example does its work on a worker thread, as
671/// every caller must.
672///
673/// ```
674/// use std::sync::Arc;
675/// use flm_core::model::doc::FragmentLayout;
676/// use flm_core::lang::copy::{copy_run_into_value, CopyError, ValueContent};
677/// use flm_core::lang::guard::run_with_worker_stack;
678/// use flm_core::lang::{
679///     build_language, parse_fragment, FlmOrigin, FlmSource, GuardPolicy, LangInputs,
680///     ParseOptions,
681/// };
682///
683/// let lang = build_language(LangInputs::new());
684/// let source = Arc::new(FlmSource::new("ab {cd}").with_origin(FlmOrigin::none()));
685/// let fragment = parse_fragment(
686///     &lang, source, FragmentLayout::default(), &ParseOptions::default(),
687/// ).expect("a parse");
688///
689/// run_with_worker_stack(|| -> Result<(), CopyError> {
690///     let root = fragment.tree().root();
691///     let run: Vec<_> = root.children().iter().collect();
692///     let value = copy_run_into_value(&run, &root, ValueContent::Own, GuardPolicy::StackBudget)?;
693///
694///     // A list root over one copy per node, each keeping its original span.
695///     assert!(value.root().is_list());
696///     assert_eq!(value.root().child_count(), run.len());
697///     assert_eq!(value.root().children().iter().next().unwrap().span(), run[0].span());
698///     Ok(())
699/// }).expect("a worker thread")?;
700/// # Ok::<(), CopyError>(())
701/// ```
702pub fn copy_run_into_value(
703    nodes: &[NodeRef<'_, Flm>],
704    anchor: &NodeRef<'_, Flm>,
705    content: ValueContent,
706    guard: GuardPolicy,
707) -> Result<Arc<NodeTree<Flm>>, CopyError> {
708    let pieces: Vec<ValuePiece<'_, '_>> = nodes.iter().copied().map(ValuePiece::Node).collect();
709    copy_pieces_into_value(&pieces, anchor, content, guard)
710}
711
712/// Copies `pieces` (value pieces, [`ValuePiece`]) into a new value tree and
713/// returns it: a list node holding, in order, a copy of each node with its
714/// subtree, a new text node for each text, and a new node for each [synthesized
715/// piece](SynthesizedPiece) and [command piece](CommandPiece), holding the copy
716/// of that piece's own pieces.
717///
718/// The root spans the pieces that have a place in a source (nodes, synthesized
719/// pieces and command pieces), from the first to the last, or is an empty span
720/// at `anchor`'s start when there is none. A text piece has no place in the
721/// document and gets an empty span at `anchor`'s start. The nodes may belong to
722/// any tree (the tree a node was parsed in, or a tree derived from it, such as
723/// the one techy's key-value reader builds), and each copy keeps the span,
724/// source, parsing state and element of the node it was made from.
725///
726/// `content` is the purpose of the copy ([`ValueContent`]). For a copy of the
727/// value's own, every node is copied unchanged. For a copy shown again, each
728/// node (including the nodes inside the pieces of a synthesized or command
729/// piece) is copied as its element says ([`copied_as`]): itself over the copies
730/// of its children, nothing, or one new node in its place, at its span and
731/// under its parsing state. The node of a synthesized or command piece itself
732/// is added as given: the elements are asked only about nodes copied out of a
733/// tree, not about the nodes the caller creates.
734///
735/// Call this function on a worker thread, as for [`copy_run_into_value`].
736///
737/// # Errors
738///
739/// [`CopyError::NestingTooDeep`] when the content is nested deeper than `guard`
740/// allows; [`CopyError::Failed`] when building the copy fails, which is an
741/// error in the program, not something a document causes.
742pub fn copy_pieces_into_value(
743    pieces: &[ValuePiece<'_, '_>],
744    anchor: &NodeRef<'_, Flm>,
745    content: ValueContent,
746    guard: GuardPolicy,
747) -> Result<Arc<NodeTree<Flm>>, CopyError> {
748    let mut visitor = CopyRun { pieces, anchor: *anchor, content };
749    let tree = guard::restager(&mut visitor, guard).restage(anchor.tree())?;
750    Ok(Arc::new(tree))
751}
752
753#[cfg(test)]
754mod tests {
755    use super::*;
756    use crate::model::doc::FragmentLayout;
757    use crate::lang::{FlmOrigin, LangInputs, ParseOptions, build_language, parse_fragment};
758    use techy::source::Source;
759
760    #[test]
761    fn a_copied_run_becomes_a_list_root_over_copies_keeping_their_spans() {
762        let lang = build_language(LangInputs::new());
763        let source = Arc::new(Source::new("ab {cd}").with_origin(FlmOrigin::none()));
764        let fragment =
765            parse_fragment(&lang, source, FragmentLayout::default(), &ParseOptions::default())
766                .expect("a parse");
767        let root = fragment.tree().root();
768        let nodes: Vec<_> = root.children().iter().collect();
769        let value = copy_run_into_value(&nodes, &root, ValueContent::Own, GuardPolicy::StackBudget).expect("copied");
770        let copied = value.root();
771        assert!(copied.is_list());
772        assert_eq!(copied.child_count(), nodes.len());
773        let spans: Vec<_> = copied.children().iter().map(|n| n.span().clone()).collect();
774        let originals: Vec<_> = nodes.iter().map(|n| n.span().clone()).collect();
775        assert_eq!(spans, originals);
776    }
777
778    #[test]
779    fn a_text_piece_becomes_a_text_node_beside_the_copied_nodes() {
780        let lang = build_language(LangInputs::new());
781        let source = Arc::new(Source::new("ab {cd}").with_origin(FlmOrigin::none()));
782        let fragment =
783            parse_fragment(&lang, source, FragmentLayout::default(), &ParseOptions::default())
784                .expect("a parse");
785        let root = fragment.tree().root();
786        let group = root.children().iter().next_back().expect("the group");
787        let pieces = [ValuePiece::Text("xy"), ValuePiece::Node(group)];
788        let value = copy_pieces_into_value(&pieces, &root, ValueContent::Own, GuardPolicy::StackBudget).expect("copied");
789        let children: Vec<_> = value.root().children().iter().collect();
790        assert_eq!(children.len(), 2);
791        assert_eq!(children[0].chars(), Some("xy"));
792        assert!(children[1].is_group());
793        assert_eq!(value.root().span(), group.span());
794    }
795
796    #[test]
797    fn a_synthesized_piece_becomes_a_fresh_node_holding_its_own_pieces_in_its_slot() {
798        use crate::model::element::ElementSpec;
799        let lang = build_language(LangInputs::new());
800        let source = Arc::new(Source::new("ab {cd}").with_origin(FlmOrigin::none()));
801        let fragment =
802            parse_fragment(&lang, source, FragmentLayout::default(), &ParseOptions::default())
803                .expect("a parse");
804        let root = fragment.tree().root();
805        let group = root.children().iter().next_back().expect("the group");
806        let spec = Arc::new(FlmSynthesizedSpec::new(Arc::new(ElementSpec::new("t.box"))));
807        let span = SourceSpan::new(group.span().source(), 1..2);
808        let boxed = SynthesizedPiece {
809            spec,
810            slot: "body",
811            span: span.clone(),
812            state: Arc::clone(root.parsing_state()),
813            body: vec![ValuePiece::Text("xy"), ValuePiece::Node(group)],
814            payload: None,
815        };
816        let value = copy_pieces_into_value(&[ValuePiece::Synthesized(&boxed)], &root, ValueContent::Own, GuardPolicy::StackBudget)
817            .expect("copied");
818        // The root spans the synthesized node, which holds the text — at its
819        // own start, not the anchor's — and the copied group in its slot.
820        assert_eq!(value.root().span(), &span);
821        let node = value.root().children().iter().next().expect("the node");
822        assert_eq!(node.ext().element.name.as_str(), "t.box");
823        let body: Vec<_> = node.children().iter().collect();
824        assert_eq!(body.len(), 2);
825        assert_eq!(body[0].chars(), Some("xy"));
826        assert_eq!(body[0].span().start(), 1);
827        assert!(body[1].is_group());
828        assert_eq!(body[1].span(), group.span());
829    }
830
831    #[test]
832    fn a_synthesized_piece_carries_its_payload_and_may_hold_nothing() {
833        use crate::model::element::ElementSpec;
834        use techy::serialize::SerialValue;
835        #[derive(Debug)]
836        struct Named(&'static str);
837        impl PresPayload for Named {
838            fn project(&self) -> SerialValue {
839                SerialValue::Str(self.0.to_string())
840            }
841        }
842        let lang = build_language(LangInputs::new());
843        let source = Arc::new(Source::new("ab").with_origin(FlmOrigin::none()));
844        let fragment =
845            parse_fragment(&lang, source, FragmentLayout::default(), &ParseOptions::default())
846                .expect("a parse");
847        let root = fragment.tree().root();
848        let spec = Arc::new(FlmSynthesizedSpec::new(Arc::new(ElementSpec::new("t.mark"))));
849        let marked = SynthesizedPiece {
850            spec,
851            slot: "body",
852            span: root.span().clone(),
853            state: Arc::clone(root.parsing_state()),
854            body: Vec::new(),
855            payload: Some(Arc::new(Named("here"))),
856        };
857        let value = copy_pieces_into_value(&[ValuePiece::Synthesized(&marked)], &root, ValueContent::Own, GuardPolicy::StackBudget)
858            .expect("built");
859        let node = value.root().children().iter().next().expect("the node");
860        assert_eq!(node.child_count(), 0);
861        let payload = node.ext().payload.as_deref().expect("a payload");
862        assert_eq!(payload.downcast_ref::<Named>().map(|named| named.0), Some("here"));
863    }
864
865    #[test]
866    fn an_empty_run_becomes_an_empty_list_at_the_anchor_s_start() {
867        let lang = build_language(LangInputs::new());
868        let source = Arc::new(Source::new("x").with_origin(FlmOrigin::none()));
869        let fragment =
870            parse_fragment(&lang, source, FragmentLayout::default(), &ParseOptions::default())
871                .expect("a parse");
872        let root = fragment.tree().root();
873        let value = copy_run_into_value(&[], &root, ValueContent::Own, GuardPolicy::StackBudget).expect("copied");
874        assert_eq!(value.root().child_count(), 0);
875        assert_eq!(value.root().span().start(), root.span().start());
876    }
877
878    /// A language where `\gone{…}` answers nothing in a copy shown again and
879    /// `\held{…}` a stand-in of the element `t.stand-in` carrying the payload
880    /// `Named("held")`.
881    mod asking {
882        use super::*;
883        use crate::lang::mint::{ArgDef, ElementDef, SyntaxDef};
884        use crate::lang::BuiltLang;
885        use crate::model::aspects::{InCopy, StandIn};
886        use crate::model::element::ElementSpec;
887        use techy::serialize::SerialValue;
888
889        #[derive(Debug)]
890        struct Named(&'static str);
891
892        impl PresPayload for Named {
893            fn project(&self) -> SerialValue {
894                SerialValue::Str(self.0.to_string())
895            }
896        }
897
898        struct Gone;
899
900        impl InCopy for Gone {
901            fn in_copy(&self, _node: &NodeRef<'_, Flm>, _purpose: ValueContent) -> CopiedAs {
902                CopiedAs::Nothing
903            }
904        }
905
906        struct Held;
907
908        impl InCopy for Held {
909            fn in_copy(&self, _node: &NodeRef<'_, Flm>, _purpose: ValueContent) -> CopiedAs {
910                let spec = FlmSynthesizedSpec::new(Arc::new(ElementSpec::new("t.stand-in")));
911                CopiedAs::StandIn(StandIn { spec: Arc::new(spec), payload: Some(Arc::new(Named("held"))) })
912            }
913        }
914
915        fn language() -> BuiltLang {
916            let mut inputs = LangInputs::new();
917            let aspects: [(&str, Arc<dyn InCopy>); 2] = [("gone", Arc::new(Gone)), ("held", Arc::new(Held))];
918            for (name, aspect) in aspects {
919                inputs.elements.push(ElementDef::new(
920                    "t",
921                    [name],
922                    SyntaxDef::Macro { args: vec![ArgDef::mandatory("text")] },
923                    Arc::new(ElementSpec::new(format!("t.{name}")).with::<dyn InCopy>(aspect)),
924                ));
925            }
926            build_language(inputs)
927        }
928
929        fn parse(lang: &BuiltLang, text: &str) -> crate::model::doc::Fragment {
930            let source = Arc::new(Source::new(text).with_origin(FlmOrigin::none()));
931            parse_fragment(lang, source, FragmentLayout::Inline, &ParseOptions::default()).expect("a parse")
932        }
933
934        /// `node` and its descendants, in document order.
935        fn subtree<'t>(node: &NodeRef<'t, Flm>) -> Vec<NodeRef<'t, Flm>> {
936            std::iter::once(*node).chain(node.descendants()).collect()
937        }
938
939        /// The element names of `node`'s subtree, `node` included, in document
940        /// order.
941        fn elements(node: &NodeRef<'_, Flm>) -> Vec<String> {
942            subtree(node).iter().map(|node| node.ext().element.name.to_string()).collect()
943        }
944
945        #[test]
946        fn a_copy_shown_again_copies_each_node_as_its_element_answers_at_every_depth() {
947            let lang = language();
948            let fragment = parse(&lang, r"a\gone{b}{c\held{d}}");
949            let root = fragment.tree().root();
950            let nodes: Vec<_> = root.children().iter().collect();
951            let value = copy_run_into_value(&nodes, &root, ValueContent::Shown, GuardPolicy::StackBudget)
952                .expect("copied");
953            let copied: Vec<_> = value.root().children().iter().collect();
954            // The text and the group are copied, keeping their spans; `\gone`
955            // is not there at all.
956            assert_eq!(copied.len(), 2);
957            assert_eq!(copied[0].chars(), Some("a"));
958            assert_eq!(copied[0].span(), nodes[0].span());
959            assert!(copied[1].is_group());
960            assert_eq!(copied[1].span(), nodes[2].span());
961            // Inside the group, `\held` is one fresh node of the stand-in
962            // element, at the original's span, holding no child and carrying
963            // the payload; what `\held` held is not copied.
964            let inner: Vec<_> = copied[1].children().iter().collect();
965            assert_eq!(inner.len(), 2);
966            let original = nodes[2].children().iter().nth(1).expect("the original");
967            assert_eq!(inner[1].ext().element.name.as_str(), "t.stand-in");
968            assert_eq!(inner[1].span(), original.span());
969            assert_eq!(inner[1].child_count(), 0);
970            let payload = inner[1].ext().payload.as_deref().expect("a payload");
971            assert_eq!(payload.downcast_ref::<Named>().map(|named| named.0), Some("held"));
972            assert!(!elements(&value.root()).iter().any(|name| name == "t.gone" || name == "t.held"));
973        }
974
975        #[test]
976        fn a_copy_of_the_value_s_own_is_verbatim_whatever_the_elements_answer() {
977            let lang = language();
978            let fragment = parse(&lang, r"a\gone{b}{c\held{d}}");
979            let root = fragment.tree().root();
980            let nodes: Vec<_> = root.children().iter().collect();
981            let value = copy_run_into_value(&nodes, &root, ValueContent::Own, GuardPolicy::StackBudget)
982                .expect("copied");
983            let originals: Vec<String> = nodes.iter().flat_map(elements).collect();
984            let copied: Vec<String> = value.root().children().iter().flat_map(|node| elements(&node)).collect();
985            assert_eq!(copied, originals);
986            let spans: Vec<_> = value.root().descendants().map(|node| node.span().clone()).collect();
987            let original_spans: Vec<_> =
988                nodes.iter().flat_map(subtree).map(|node| node.span().clone()).collect();
989            assert_eq!(spans, original_spans);
990        }
991
992        #[test]
993        fn a_copy_shown_again_asks_the_pieces_of_a_synthesized_piece_and_stages_the_piece_as_given() {
994            let lang = language();
995            let fragment = parse(&lang, r"\held{x}\gone{y}");
996            let root = fragment.tree().root();
997            let nodes: Vec<_> = root.children().iter().collect();
998            let spec = Arc::new(FlmSynthesizedSpec::new(Arc::new(ElementSpec::new("t.box"))));
999            let boxed = SynthesizedPiece {
1000                spec,
1001                slot: "body",
1002                span: root.span().clone(),
1003                state: Arc::clone(root.parsing_state()),
1004                body: nodes.iter().copied().map(ValuePiece::Node).collect(),
1005                payload: None,
1006            };
1007            let value = copy_pieces_into_value(
1008                &[ValuePiece::Synthesized(&boxed)],
1009                &root,
1010                ValueContent::Shown,
1011                GuardPolicy::StackBudget,
1012            )
1013            .expect("copied");
1014            let node = value.root().children().iter().next().expect("the box");
1015            assert_eq!(node.ext().element.name.as_str(), "t.box");
1016            let body: Vec<String> = node.children().iter().map(|n| n.ext().element.name.to_string()).collect();
1017            assert_eq!(body, ["t.stand-in"]);
1018        }
1019
1020        #[test]
1021        fn the_recursion_guard_answers_over_a_copy_shown_again() {
1022            let lang = language();
1023            let depth = 40;
1024            let text = format!("{}x{}", "{".repeat(depth), "}".repeat(depth));
1025            let fragment = parse(&lang, &text);
1026            let root = fragment.tree().root();
1027            let nodes: Vec<_> = root.children().iter().collect();
1028            let shown = copy_run_into_value(&nodes, &root, ValueContent::Shown, GuardPolicy::DepthLimit(10));
1029            assert!(matches!(shown, Err(CopyError::NestingTooDeep { .. })), "{shown:?}");
1030            let own = copy_run_into_value(&nodes, &root, ValueContent::Own, GuardPolicy::DepthLimit(10));
1031            assert!(matches!(own, Err(CopyError::NestingTooDeep { .. })), "{own:?}");
1032        }
1033    }
1034}