Skip to main content

flm_core/dump/
project.rs

1//! The projection: a one-way rendering of a tree, a node, a computed table or a
2//! diagnostic as a techy serialized value ([`SerialValue`]), in a vocabulary
3//! this library owns and keeps stable.
4//!
5//! The projection is what the library's tests compare, usually through a JSON
6//! [golden file](crate::dump::golden), and what `flm dump --view compact`
7//! prints. A parsed tree and a lowered (presentation) tree project in the same
8//! shape. The projection shows what each node means: the type name of the
9//! element of every callable and group node (`elem`), text runs by their text (`chars`),
10//! comments and nested list nodes by their kind (`kind`), arguments by name
11//! (`args`), children, the body of an environment-shaped node (`body`), a
12//! presentation node's payload through [`PresPayload::project`], and, on
13//! request, spans as `line:col`. It never shows a parsing state, a techy
14//! specification or a node id. Because the vocabulary belongs to this library
15//! rather than to techy, a change in techy's serialized layout does not change
16//! a golden file. A projection cannot be read back into a tree; the wire form
17//! of [`crate::dump::session`] is the form that reads back.
18//!
19//! Use a [`Projector`] (or the free functions [`project_tree`],
20//! [`project_node`], [`project_nodes`], [`project_diagnostic`],
21//! [`project_diagnostics`] and [`node_ref_value`], each of which builds one for
22//! a single call) with [`ProjectOptions`] to choose what is shown beyond the
23//! structure. A table is projected through [`Projector::table`]. Render the
24//! result as text with [`to_json_pretty`](crate::dump::json::to_json_pretty).
25//!
26//! The projection descends a tree by plain recursion on the calling thread,
27//! without the [recursion guard](crate::lang::guard). A tree nested deeply
28//! enough can therefore overflow the calling thread's stack, which aborts the
29//! process. Projecting on a worker thread that the library creates
30//! ([`on_worker_thread`](crate::lang::guard::on_worker_thread)) gives it
31//! [`WORKER_STACK_SIZE`](crate::lang::guard::WORKER_STACK_SIZE) of stack, but no
32//! refusal.
33//!
34//! # The shape of a node's projection
35//!
36//! Each node projects as a map whose keys come in the order listed; a key is
37//! absent when it has nothing to show:
38//!
39//! - a text run: `{"chars": "…"}`, plus `"map": [{"len", "span"}, …]` when
40//!   source maps are requested and the run carries one;
41//! - a comment: `{"kind": "comment", "text": "…"}`;
42//! - a group: `{"elem": "flm.group", "children": […]}` (or `flm.math`,
43//!   `flm.verbatim`, `flm.opaque-wrapper`, `flm.paragraph`; a math group adds
44//!   `"form": "inline"` or `"display"` before its children);
45//! - a callable: `{"elem": "<element>", "name": "<callable name>", "args":
46//!   {"<argument name or index>": […]}, "body": […], "slots": {"<slot name or
47//!   index>": […]}, "payload": <projection>}`: the name only for callables
48//!   written as a macro or an environment, the body for the node's body slot,
49//!   every other node slot (techy's `ParsedSlot`, a part of a node's content
50//!   outside its arguments) under `slots`;
51//! - a nested list node: `{"kind": "list", "children": […]}`;
52//!
53//! plus `"span": "L:C-L:C"` on every node when spans are requested. A tree
54//! projects as the list of its root's children (the root container itself is
55//! not shown), or as a one-item list holding the root when the root is not a
56//! list node. An optional argument that was not given has no key; an argument
57//! given empty is an empty list. Arguments are keyed by their declared name,
58//! else by their index.
59//!
60//! **The `name` key shows a callable's source spelling** (the command word of a
61//! macro, the name of an environment) and nothing else. The spelling tells
62//! apart two element values that share one type name: `\section` and
63//! `\subsection` carry two different element values of the type name
64//! `flm.heading` (see [elements and
65//! aspects](crate::guide::concepts_overview#elements-and-aspects)), and the
66//! projection would not distinguish them otherwise. A callable recognized by a special character sequence has as its
67//! name the sequence that triggered it (for a paragraph break, the whitespace
68//! it matched), and the presentation and placeholder callables carry an
69//! internal key; neither is a spelling, so neither is shown, and the element's
70//! type name says what those nodes are. The element's own data
71//! ([`ElementSpec::value`](crate::model::element::ElementSpec::value)) is not
72//! shown either.
73//!
74//! # Diagnostics, tables and positions
75//!
76//! A diagnostic projects as `{"id", "severity", "span", "file"?, "data"}`: its
77//! identifier, its severity, its span as `line:col`, the canonical path of its
78//! source when the source has one, and the serialized data of its condition;
79//! never its message, which is not a stable interface.
80//!
81//! A table projects under its name: `{"<table name>": <projection>}`. The
82//! table's own [`Table::project`] produces the inner projection and renders
83//! the addresses it holds through [`ProjectCx`]: node references as
84//! `elem@line:col` ([`node_ref_value`]) and tree references as the tree id's
85//! display ([`tree_ref_value`]). [`TableProjection`] is the implementation of
86//! [`ProjectCx`] the library uses, and [`TreeSource`] supplies the trees the
87//! node references are resolved in.
88//!
89//! Positions use the source's line and column numbering (1-based unless the
90//! source sets other offsets). A span is `L:C-L:C` from its start to its
91//! exclusive end, or `L:C` when it is empty. A source too large for techy to
92//! index by line is shown with byte offsets instead: `@start-end` for a span,
93//! `b<offset>` in a node reference.
94
95use std::collections::BTreeMap;
96use std::sync::{Arc, Mutex};
97
98use techy::core::node::{BodySlotExt, NodeId, NodeKind, NodeRef, NodeTree};
99use techy::latexlike::MathGroupForm;
100use techy::serialize::SerialValue;
101use techy::source::LineIndexCache;
102
103use crate::model::addr::{NodeAddr, TreeId};
104use crate::model::doc::DocContent;
105use crate::core::run::Run;
106use crate::core::data::table::{ProjectCx, Table};
107use crate::lang::ext::{PresPayload, TextSourceMap};
108use crate::lang::flm::{Flm, FlmCallableType, FlmGroupType};
109use crate::lang::origin::{FlmDiagnostic, FlmOrigin, FlmSpan};
110
111/// The options of a projection: what it shows beyond the structure it always
112/// shows.
113///
114/// The three switches are independent. By default spans and source maps are
115/// hidden and presentation payloads are shown. Build the options with
116/// [`new`](ProjectOptions::new) and the builder methods, then pass them to
117/// [`Projector::new`] or to one of the free functions of this module.
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119pub struct ProjectOptions {
120    /// Whether every node shows its span as `line:col` (key `"span"`); off by
121    /// default.
122    pub spans: bool,
123    /// Whether presentation nodes show their payload (key `"payload"`); on by
124    /// default.
125    pub payloads: bool,
126    /// Whether text runs show their text source map, when they carry one (key
127    /// `"map"`); off by default.
128    pub source_maps: bool,
129}
130
131impl Default for ProjectOptions {
132    fn default() -> ProjectOptions {
133        ProjectOptions { spans: false, payloads: true, source_maps: false }
134    }
135}
136
137impl ProjectOptions {
138    /// Returns the default options: no spans, payloads shown, no source maps.
139    pub fn new() -> ProjectOptions {
140        ProjectOptions::default()
141    }
142
143    /// Builder: shows the span of every node.
144    pub fn with_spans(mut self) -> ProjectOptions {
145        self.spans = true;
146        self
147    }
148
149    /// Builder: hides the payloads of presentation nodes.
150    pub fn without_payloads(mut self) -> ProjectOptions {
151        self.payloads = false;
152        self
153    }
154
155    /// Builder: shows the text source maps of text runs.
156    pub fn with_source_maps(mut self) -> ProjectOptions {
157        self.source_maps = true;
158        self
159    }
160}
161
162fn text(value: impl Into<String>) -> SerialValue {
163    SerialValue::Str(value.into())
164}
165
166/// Whether a callable of this form shows its name under the `name` key: only
167/// when the name is the callable's source spelling, the command word of a macro
168/// or the name of an environment. A callable recognized by a special character
169/// sequence has the triggering sequence as its name (for a paragraph break, the
170/// matched whitespace), and the presentation and placeholder callables carry an
171/// internal key; neither is a spelling, so neither is shown.
172fn has_source_name(form: FlmCallableType) -> bool {
173    match form {
174        FlmCallableType::Macro | FlmCallableType::Environment => true,
175        FlmCallableType::Specials
176        | FlmCallableType::Placeholder
177        | FlmCallableType::Presentation => false,
178    }
179}
180
181fn map(entries: Vec<(&str, SerialValue)>) -> SerialValue {
182    SerialValue::Map(entries.into_iter().map(|(key, value)| (String::from(key), value)).collect())
183}
184
185/// Projects trees, nodes, tables and diagnostics with one set of
186/// [`ProjectOptions`], caching the line positions it computes.
187///
188/// One projector serves any number of projections, and every method takes
189/// `&self`, so all the entries of a table are projected through one projector.
190/// Turning a byte offset into a line and column requires the line starts of the
191/// source, so the projector caches them per source. The cache is behind a lock
192/// and never changes an output, so the methods need no `&mut`.
193///
194/// The free functions of this module ([`project_tree`], [`project_node`], and so
195/// on) build a projector for a single call; use a `Projector` directly when
196/// projecting more than one thing. The [module documentation](self) gives the
197/// shape of every projection.
198pub struct Projector {
199    options: ProjectOptions,
200    lines: Mutex<LineIndexCache<FlmOrigin>>,
201}
202
203impl Projector {
204    /// Creates a projector with the given options.
205    pub fn new(options: ProjectOptions) -> Projector {
206        Projector { options, lines: Mutex::new(LineIndexCache::new()) }
207    }
208
209    /// Returns the projector's options.
210    pub fn options(&self) -> &ProjectOptions {
211        &self.options
212    }
213
214    /// Projects a whole tree: the list of its root's children (the root
215    /// container itself is not shown), or a one-item list holding the root when
216    /// the root is not a list node.
217    pub fn tree(&self, tree: &NodeTree<Flm>) -> SerialValue {
218        let root = tree.root();
219        if root.is_list() {
220            self.nodes(root.children().iter())
221        } else {
222            SerialValue::List(vec![self.node(&root)])
223        }
224    }
225
226    /// Projects the given nodes, as a list of their projections.
227    pub fn nodes<'t>(&self, nodes: impl IntoIterator<Item = NodeRef<'t, Flm>>) -> SerialValue {
228        SerialValue::List(nodes.into_iter().map(|node| self.node(&node)).collect())
229    }
230
231    /// Projects one node, in the shape the [module documentation](self) gives.
232    pub fn node(&self, node: &NodeRef<'_, Flm>) -> SerialValue {
233        let mut entries: Vec<(&str, SerialValue)> = Vec::new();
234        match node.kind() {
235            NodeKind::Chars { content } => {
236                entries.push(("chars", text(content.resolve(node.span().source()))));
237                if self.options.source_maps {
238                    if let Some(source_map) = &node.ext().source_map {
239                        entries.push(("map", self.source_map(source_map)));
240                    }
241                }
242            }
243            NodeKind::Comment(comment) => {
244                entries.push(("kind", text("comment")));
245                entries.push(("text", text(comment.content.resolve(node.span().source()))));
246            }
247            NodeKind::List => {
248                entries.push(("kind", text("list")));
249                entries.push(("children", self.nodes(node.children().iter())));
250            }
251            NodeKind::Group(group) => {
252                entries.push(("elem", text(node.ext().element.name.as_str())));
253                if let Some(FlmGroupType::Math(form)) = group.group_type {
254                    let form = match form {
255                        MathGroupForm::Inline => "inline",
256                        MathGroupForm::Display => "display",
257                    };
258                    entries.push(("form", text(form)));
259                }
260                entries.push(("children", self.nodes(node.children().iter())));
261            }
262            NodeKind::Callable(data) => {
263                entries.push(("elem", text(node.ext().element.name.as_str())));
264                if has_source_name(data.callable_type) {
265                    entries.push(("name", text(&*data.name)));
266                }
267                let mut args: Vec<(String, SerialValue)> = Vec::new();
268                for (index, argument) in data.arguments.iter().enumerate() {
269                    if let Some(content) = node.argument_content_nodes(index) {
270                        let key = argument.name().map_or_else(|| index.to_string(), String::from);
271                        args.push((key, self.nodes(content.iter())));
272                    }
273                }
274                if !args.is_empty() {
275                    entries.push(("args", SerialValue::Map(args)));
276                }
277                let mut body: Option<SerialValue> = None;
278                let mut slots: Vec<(String, SerialValue)> = Vec::new();
279                for (index, slot) in data.slots.iter().enumerate() {
280                    let Some(content) = node.slot_content_nodes(index) else {
281                        continue;
282                    };
283                    let projection = self.nodes(content.iter());
284                    if body.is_none() && slot.ext.is_body() {
285                        body = Some(projection);
286                    } else {
287                        let key = slot.name().map_or_else(|| index.to_string(), String::from);
288                        slots.push((key, projection));
289                    }
290                }
291                if let Some(body) = body {
292                    entries.push(("body", body));
293                }
294                if !slots.is_empty() {
295                    entries.push(("slots", SerialValue::Map(slots)));
296                }
297                if self.options.payloads {
298                    if let Some(payload) = &node.ext().payload {
299                        entries.push(("payload", payload.project()));
300                    }
301                }
302            }
303        }
304        if self.options.spans {
305            entries.push(("span", text(self.span(node.span()))));
306        }
307        map(entries)
308    }
309
310    /// Projects a text source map as `[{"len", "span"}, …]`: for each part of
311    /// the text run, its length in bytes and the span of source text it comes
312    /// from, as `line:col`.
313    pub fn source_map(&self, source_map: &TextSourceMap) -> SerialValue {
314        SerialValue::List(
315            source_map
316                .pieces()
317                .iter()
318                .map(|piece| {
319                    map(vec![
320                        ("len", SerialValue::Int(i64::from(piece.out_len))),
321                        ("span", text(self.span(&piece.span))),
322                    ])
323                })
324                .collect(),
325        )
326    }
327
328    /// Renders a reference to a node of `tree` as `elem@line:col`: the node's
329    /// element and the position where its span starts. This is how a table entry
330    /// that points at a node is shown. A node id that `tree` does not hold
331    /// renders as `?@<the id's numeric index>`.
332    pub fn node_ref(&self, tree: &NodeTree<Flm>, node: NodeId) -> SerialValue {
333        match tree.get(node) {
334            Some(node) => {
335                text(format!("{}@{}", node.ext().element.name.as_str(), self.position(node.span())))
336            }
337            None => text(format!("?@{}", node.index())),
338        }
339    }
340
341    /// Renders a reference to a tree as the tree id's display form (`tree#0`
342    /// for a document tree, `value#3` for a synthesized value).
343    pub fn tree_ref(&self, tree: TreeId) -> SerialValue {
344        text(tree.to_string())
345    }
346
347    /// Projects one diagnostic as `{"id", "severity", "span", "file"?, "data"}`
348    /// (see the [module documentation](self)); the message is never shown.
349    pub fn diagnostic(&self, diagnostic: &FlmDiagnostic) -> SerialValue {
350        let mut entries: Vec<(&str, SerialValue)> = vec![
351            ("id", text(diagnostic.identifier())),
352            ("severity", text(diagnostic.severity().to_string())),
353            ("span", text(self.span(diagnostic.span()))),
354        ];
355        if let Some(path) = diagnostic.span().source().origin().canonical_path() {
356            entries.push(("file", text(path)));
357        }
358        entries.push(("data", SerialValue::from(diagnostic.data().serializable_data())));
359        map(entries)
360    }
361
362    /// Projects the given diagnostics, as a list of their projections.
363    pub fn diagnostics<'a>(
364        &self,
365        diagnostics: impl IntoIterator<Item = &'a FlmDiagnostic>,
366    ) -> SerialValue {
367        SerialValue::List(
368            diagnostics.into_iter().map(|diagnostic| self.diagnostic(diagnostic)).collect(),
369        )
370    }
371
372    /// Renders a span as `L:C-L:C` (start, exclusive end), or `L:C` when the
373    /// span is empty; as byte offsets (`@start-end`, or `@offset` when empty)
374    /// when the source is too large for techy to index by line.
375    pub fn span(&self, span: &FlmSpan) -> String {
376        let mut lines = self.lines.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
377        match lines.line_col_span(span.source(), span.range()) {
378            Some(((line, col), (end_line, end_col))) => {
379                if span.is_empty() {
380                    format!("{line}:{col}")
381                } else {
382                    format!("{line}:{col}-{end_line}:{end_col}")
383                }
384            }
385            None if span.is_empty() => format!("@{}", span.start()),
386            None => format!("@{}-{}", span.start(), span.end()),
387        }
388    }
389
390    /// Renders the start of a span as `L:C`, or as `b<offset>` when the source is
391    /// too large for techy to index by line. This is the position part of a node
392    /// reference ([`node_ref`](Projector::node_ref)).
393    pub fn position(&self, span: &FlmSpan) -> String {
394        let mut lines = self.lines.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
395        match lines.line_col(span.source(), span.start()) {
396            Some((line, col)) => format!("{line}:{col}"),
397            None => format!("b{}", span.start()),
398        }
399    }
400}
401
402impl std::fmt::Debug for Projector {
403    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
404        f.debug_struct("Projector").field("options", &self.options).finish_non_exhaustive()
405    }
406}
407
408/// Projects a whole tree with a projector built for this call
409/// ([`Projector::tree`]).
410pub fn project_tree(tree: &NodeTree<Flm>, options: &ProjectOptions) -> SerialValue {
411    Projector::new(*options).tree(tree)
412}
413
414/// Projects one node with a projector built for this call
415/// ([`Projector::node`]).
416pub fn project_node(node: &NodeRef<'_, Flm>, options: &ProjectOptions) -> SerialValue {
417    Projector::new(*options).node(node)
418}
419
420/// Projects the given nodes, as a list, with a projector built for this call
421/// ([`Projector::nodes`]).
422pub fn project_nodes<'t>(
423    nodes: impl IntoIterator<Item = NodeRef<'t, Flm>>,
424    options: &ProjectOptions,
425) -> SerialValue {
426    Projector::new(*options).nodes(nodes)
427}
428
429/// Projects one diagnostic with a projector built for this call
430/// ([`Projector::diagnostic`]).
431pub fn project_diagnostic(diagnostic: &FlmDiagnostic, options: &ProjectOptions) -> SerialValue {
432    Projector::new(*options).diagnostic(diagnostic)
433}
434
435/// Projects the given diagnostics, as a list, with a projector built for this
436/// call ([`Projector::diagnostics`]).
437pub fn project_diagnostics<'a>(
438    diagnostics: impl IntoIterator<Item = &'a FlmDiagnostic>,
439    options: &ProjectOptions,
440) -> SerialValue {
441    Projector::new(*options).diagnostics(diagnostics)
442}
443
444// --- tables: the projection context ------------------------------------------------------
445
446/// A set of trees looked up by [`TreeId`], in which the node references of a
447/// table are resolved while the table is projected.
448///
449/// Three implementations are provided: a document's parsed trees
450/// ([`DocContent`]), a run's frozen trees ([`Run`], the trees its tables were
451/// computed over), and a map from tree id to tree that a test assembles.
452///
453/// The id of a [synthesized
454/// value](crate::guide::concepts_overview#synthesized-values) (a small tree a
455/// stage builds) is found in none of them, because such a tree exists only
456/// inside the stage invocation that built it (see [`crate::model::addr`]). A
457/// table holding one therefore projects the tree **inline**, through
458/// [`ProjectCx::tree`], and never by its id.
459pub trait TreeSource {
460    /// Returns the tree with this id, or `None` when this set does not hold it.
461    fn tree_of(&self, id: TreeId) -> Option<&NodeTree<Flm>>;
462}
463
464impl TreeSource for DocContent {
465    fn tree_of(&self, id: TreeId) -> Option<&NodeTree<Flm>> {
466        self.tree(id).map(|tree| &**tree)
467    }
468}
469
470impl TreeSource for Run {
471    /// Looks the id up among the run's frozen trees, the trees its tables were
472    /// computed over.
473    fn tree_of(&self, id: TreeId) -> Option<&NodeTree<Flm>> {
474        self.frozen_tree(id).map(|tree| &**tree)
475    }
476}
477
478impl TreeSource for BTreeMap<TreeId, Arc<NodeTree<Flm>>> {
479    fn tree_of(&self, id: TreeId) -> Option<&NodeTree<Flm>> {
480        self.get(&id).map(|tree| &**tree)
481    }
482}
483
484/// The context through which a table projects itself: a [`Projector`] and the
485/// trees ([`TreeSource`]) in which the table's node references are resolved.
486///
487/// This is the implementation of [`ProjectCx`] the library uses, so that every
488/// table's [`project`](Table::project) renders node addresses and tree ids in
489/// the projection's vocabulary. Create one with
490/// [`Projector::table_projection`], or let [`Projector::table`] create it.
491pub struct TableProjection<'a> {
492    projector: &'a Projector,
493    trees: &'a dyn TreeSource,
494}
495
496impl ProjectCx for TableProjection<'_> {
497    /// Renders the address as `elem@line:col`, looking the node up in the tree
498    /// the address designates. An address whose tree is not in the
499    /// [`TreeSource`] renders as `?@<tree>/<node index>`. This happens when a
500    /// table stores the address of a node in a synthesized value, which
501    /// [`crate::model::addr`] forbids, or of a tree the source does not hold;
502    /// the projection then shows the error instead of hiding it.
503    fn node_ref(&self, addr: NodeAddr) -> SerialValue {
504        match self.trees.tree_of(addr.tree) {
505            Some(tree) => self.projector.node_ref(tree, addr.node),
506            None => text(format!("?@{}/{}", addr.tree, addr.node.index())),
507        }
508    }
509
510    fn tree_ref(&self, id: TreeId) -> SerialValue {
511        self.projector.tree_ref(id)
512    }
513
514    /// Projects the tree inline, as [`Projector::tree`] does.
515    fn tree(&self, tree: &NodeTree<Flm>) -> SerialValue {
516        self.projector.tree(tree)
517    }
518}
519
520impl Projector {
521    /// Creates the context through which a table projects itself, resolving node
522    /// references in `trees`.
523    pub fn table_projection<'a>(&'a self, trees: &'a dyn TreeSource) -> TableProjection<'a> {
524        TableProjection { projector: self, trees }
525    }
526
527    /// Projects a table under its name, `{"<name>": <projection>}`, resolving
528    /// its node references in `trees`.
529    ///
530    /// The inner projection is the table's own [`Table::project`], called
531    /// through a [`table_projection`](Projector::table_projection) over `trees`;
532    /// [`project_table`] then puts it under `name`. Pass the table's registered
533    /// name: a table is identified by its name, never by its Rust type.
534    ///
535    /// # Examples
536    ///
537    /// ```
538    /// use std::collections::BTreeMap;
539    /// use std::sync::Arc;
540    ///
541    /// use flm_core::model::addr::TreeId;
542    /// use flm_core::core::data::table::{ProjectCx, Table};
543    /// use flm_core::dump::{ProjectOptions, Projector, to_json};
544    /// use flm_core::lang::flm::Flm;
545    /// use flm_core::techy::core::node::NodeTree;
546    /// use flm_core::techy::serialize::SerialValue;
547    ///
548    /// #[derive(Default)]
549    /// struct Count(i64);
550    ///
551    /// impl Table for Count {
552    ///     fn absorb(&mut self, piece: Count) {
553    ///         self.0 += piece.0;
554    ///     }
555    ///     fn project(&self, _cx: &dyn ProjectCx) -> SerialValue {
556    ///         SerialValue::Int(self.0)
557    ///     }
558    /// }
559    ///
560    /// // This table holds no node address, so an empty set of trees will do.
561    /// let trees: BTreeMap<TreeId, Arc<NodeTree<Flm>>> = BTreeMap::new();
562    /// let projector = Projector::new(ProjectOptions::new());
563    /// let value = projector.table("example.count", &Count(3), &trees);
564    /// assert_eq!(to_json(&value)?, r#"{"example.count":3}"#);
565    /// # Ok::<(), flm_core::dump::JsonError>(())
566    /// ```
567    pub fn table<T: Table>(&self, name: &str, table: &T, trees: &dyn TreeSource) -> SerialValue {
568        project_table(name, table.project(&self.table_projection(trees)))
569    }
570}
571
572/// Puts a table's projection under the table's name: `{"<name>": <projection>}`.
573///
574/// A table is identified by its registered name rather than by its Rust type,
575/// so the name is what `flm dump` and a golden file show. `projection` is what
576/// the table's [`Table::project`] returned; [`Projector::table`] computes it and
577/// calls this function in one step.
578pub fn project_table(name: &str, projection: SerialValue) -> SerialValue {
579    map(vec![(name, projection)])
580}
581
582/// Renders a reference to a node of `tree` as `elem@line:col`, with a projector
583/// built for this call ([`Projector::node_ref`]).
584pub fn node_ref_value(tree: &NodeTree<Flm>, node: NodeId, options: &ProjectOptions) -> SerialValue {
585    Projector::new(*options).node_ref(tree, node)
586}
587
588/// Renders a reference to a tree as the tree id's display form, `tree#0` or
589/// `value#3` ([`Projector::tree_ref`]).
590pub fn tree_ref_value(tree: TreeId) -> SerialValue {
591    text(tree.to_string())
592}
593
594/// Projects a presentation payload on its own ([`PresPayload::project`]): the
595/// same value a node's projection shows under `"payload"`.
596pub fn project_payload(payload: &dyn PresPayload) -> SerialValue {
597    payload.project()
598}