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