Skip to main content

flm_core/model/
doc.rs

1//! Documents and fragments: the parsed source a document is made of, how its
2//! trees are placed, and the walk that defines document order.
3//!
4//! A fragment is one piece of source as the parser delivered it (its tree, its
5//! source, its parse diagnostics); a tree is one placement of a fragment's node
6//! tree in a document, numbered by the document's arena; a document is its
7//! content (the tree arena, the traversal list and the resolution map) and the
8//! option values bound on it, and nothing else. See [documents, fragments, and
9//! the corpus](crate::guide::concepts_overview#documents-fragments-and-the-corpus).
10//!
11//! A [`Fragment`] also records how the content at its top level is laid out
12//! ([`FragmentLayout`]). It is shared as `Arc<Fragment>` and has no identifier
13//! of its own: its identity is the shared pointer, so one fragment may be used
14//! by several documents at once.
15//!
16//! A document ([`Doc`]) holds its content ([`DocContent`]) and the option values
17//! set on it ([`OptionValues`]). The content has exactly three parts:
18//!
19//! - the **tree arena**, which numbers every tree added to the document with a
20//!   [`TreeId`] in the order the trees are added; adding one `Arc<Fragment>`
21//!   twice makes two trees, each with its own computed data;
22//! - the **traversal list**, the trees the walk visits in their own right, in
23//!   order;
24//! - the **resolution map**, which records the node at which each placed tree
25//!   is entered: the node *places* that tree.
26//!
27//! A document has no structure beyond that: no front matter, no chapters, no
28//! named parts. The structure of a document comes from the headings in its
29//! content and is computed by a stage, so that there is only one account of how
30//! a document nests.
31//!
32//! The usual way to build a document's content is [`assemble`], which parses a
33//! primary file and the files it includes; [`DocContent::place`],
34//! [`DocContent::add_tree`] and [`DocContent::resolve`] build one tree by tree.
35//!
36//! # The walk
37//!
38//! [`DocContent::walk`] defines document order, and it is the only definition
39//! the library has. The walk visits the trees of the traversal list in order,
40//! enters each tree at most once, and enters a tree that a node places at that
41//! node: the placed tree's nodes come right after the placing node, before the
42//! placing node's own children. Everything that comes before the placed tree in
43//! document order is therefore the placing node and everything that comes
44//! before it. Every notion of "earlier in the document" (numbering, the order of
45//! notes, the order of citations) uses this one operation, so a placed tree
46//! needs no special handling anywhere else. [`DocContent::walk_nodes`] and
47//! [`DocContent::walk_trees`] keep the nodes alone and the trees alone.
48//!
49//! The walk ([`Walk`]) runs over any [`WalkSource`]: something that gives trees
50//! by identifier, the trees of its traversal list, and which node places which
51//! tree. [`DocContent`] is the source of the trees as parsed; a run is the
52//! source of its frozen trees, what each tree became after the rewrites
53//! ([`StageCx::walk`](crate::core::run::StageCx::walk)). Both use [`Walk`], so
54//! document order is the same for both.
55//!
56//! Document order is neither the order of the arena nor the order in which node
57//! addresses sort; see [`crate::model::addr`].
58//!
59//! # What a document does not hold
60//!
61//! The data that stages compute, and the diagnostics they report, belong to
62//! the run that computed them, not to the document: one document may be
63//! rendered to several formats, or checked and then rendered, and nothing
64//! about it may depend on which plan runs. The diagnostics of the parse are
65//! kept in the fragment ([`Fragment::diags`]). Synthesized values (small trees
66//! a stage builds while a run is under way) are not part of the arena either;
67//! the run numbers them (see [`TreeId`]).
68//!
69//! [`assemble`]: crate::model::assemble::assemble
70
71use std::collections::BTreeMap;
72use std::fmt;
73use std::sync::Arc;
74
75use techy::core::node::{Descendants, NodeRef, NodeTree};
76
77use crate::model::addr::{NodeAddr, TreeId};
78use crate::model::options::OptionValues;
79use crate::lang::flm::Flm;
80use crate::lang::origin::{FlmDiagnostics, FlmSource};
81
82/// How the content at the top level of a fragment is laid out when a run
83/// builds block structure: as blocks, as inline content, or as blocks only
84/// when it holds a block.
85///
86/// The block-structure rewrite ([`crate::lang::rewrites::blocks`]) reads it.
87/// It is recorded on the fragment rather than on the document because it is a
88/// property of the text: a title is inline content in every document that
89/// uses it.
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]
91#[serde(rename_all = "kebab-case")]
92pub enum FragmentLayout {
93    /// The top level holds blocks: paragraphs are built from its content.
94    Blocks,
95    /// Everything at the top level is inline content. An element whose block
96    /// role is not inline is reported as an error there, and is left where it
97    /// is written.
98    Inline,
99    /// Inline content, unless the top level holds a paragraph break or an
100    /// element whose block role is
101    /// [`Block`](crate::model::aspects::BlockRole::Block); then the whole top
102    /// level is laid out as blocks. This is the default.
103    #[default]
104    InlineOrBlocks,
105}
106
107/// A fragment: one piece of source as the parser delivered it, with its tree,
108/// the source it came from, the diagnostics of the parse, and the layout of its
109/// top level ([`FragmentLayout`]).
110///
111/// The tree is exactly what the parse delivered, source comments included.
112/// Expanding user definitions and building block structure are rewrite stages
113/// of a run, and the trees they produce are stored by the run, apart from the
114/// fragment. Because the fragment keeps the parse as written, one shared
115/// fragment can be used by several documents with different configurations,
116/// and a tool can recover the author's own text from it.
117///
118/// A fragment is shared as `Arc<Fragment>` and has no identifier: its
119/// identity is the pointer, and within one document each placement of it is
120/// identified by a [`TreeId`]. Create one with
121/// [`parse_fragment`](crate::lang::parse_fragment), or with [`Fragment::new`]
122/// from a tree obtained some other way.
123pub struct Fragment {
124    source: Arc<FlmSource>,
125    tree: Arc<NodeTree<Flm>>,
126    diags: FlmDiagnostics,
127    layout: FragmentLayout,
128}
129
130impl Fragment {
131    /// A fragment holding the parsed tree `tree`, the source it was parsed
132    /// from, the diagnostics of the parse and the layout of its top level.
133    ///
134    /// [`parse_fragment`](crate::lang::parse_fragment) is the usual way to
135    /// obtain a fragment; this constructor is for a tree built or read back
136    /// from storage elsewhere. No check is made that the parts belong
137    /// together.
138    pub fn new(
139        source: Arc<FlmSource>,
140        tree: Arc<NodeTree<Flm>>,
141        diags: FlmDiagnostics,
142        layout: FragmentLayout,
143    ) -> Fragment {
144        Fragment { source, tree, diags, layout }
145    }
146
147    /// The source the tree was parsed from; its origin (such as a file name)
148    /// is what diagnostics report.
149    pub fn source(&self) -> &Arc<FlmSource> {
150        &self.source
151    }
152
153    /// The tree, exactly as the parse produced it.
154    pub fn tree(&self) -> &Arc<NodeTree<Flm>> {
155        &self.tree
156    }
157
158    /// The diagnostics the parse produced. Diagnostics reported later, while
159    /// stages run, are kept by the run instead.
160    pub fn diags(&self) -> &FlmDiagnostics {
161        &self.diags
162    }
163
164    /// How the top level is laid out when block structure is built.
165    pub fn layout(&self) -> FragmentLayout {
166        self.layout
167    }
168}
169
170impl fmt::Debug for Fragment {
171    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172        f.debug_struct("Fragment")
173            .field("source", &self.source.origin())
174            .field("nodes", &self.tree.node_count())
175            .field("diags", &self.diags.len())
176            .field("layout", &self.layout)
177            .finish()
178    }
179}
180
181/// The error of [`DocContent::resolve`]: why a placement was not recorded.
182///
183/// Each variant holds the trees and nodes involved, so a caller can report the
184/// problem without computing them again.
185#[derive(Debug, Clone, PartialEq, Eq)]
186pub enum PlacementError {
187    /// Another node already places the target tree. The walk enters each tree
188    /// once, so one node at most may place a tree.
189    AlreadyPlaced {
190        /// The tree that would have been placed twice.
191        target: TreeId,
192        /// The node that already places it.
193        first: NodeAddr,
194        /// The node that tried to place it as well.
195        second: NodeAddr,
196    },
197    /// The node already places a tree. A node may place one tree at most.
198    SiteTaken {
199        /// The node that would have placed a second tree.
200        site: NodeAddr,
201        /// The tree it already places.
202        target: TreeId,
203    },
204    /// The identifier is not that of a tree of this document: it identifies a
205    /// synthesized value, or its index is past the end of the arena. Returned
206    /// for the target tree and for the tree of the placing node alike.
207    UnknownTree(TreeId),
208    /// The placing node belongs to the target tree itself, and the walk could
209    /// not enter a tree from inside itself.
210    SelfPlacement(TreeId),
211}
212
213impl fmt::Display for PlacementError {
214    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215        match self {
216            PlacementError::AlreadyPlaced { target, first, second } => write!(
217                f,
218                "a tree can be placed at one node only: {target} is already placed at \
219                 {first:?} and cannot also be placed at {second:?}"
220            ),
221            PlacementError::SiteTaken { site, target } => {
222                write!(f, "a node can place one tree only: {site:?} already places {target}")
223            }
224            PlacementError::UnknownTree(tree) => write!(f, "{tree} is not a tree of this document"),
225            PlacementError::SelfPlacement(tree) => write!(f, "{tree} cannot be placed at one of its own nodes"),
226        }
227    }
228}
229
230impl std::error::Error for PlacementError {}
231
232/// The content of a document: its tree arena, its traversal list and its
233/// resolution map.
234///
235/// It is built once, by adding trees and recording placements, and then only
236/// read: several runs may share one document, so nothing about it changes while
237/// a run is under way. The [module documentation](self) describes the three
238/// parts and the walk that they define.
239///
240/// [`assemble`](crate::model::assemble::assemble) builds the content of a
241/// document from its files; [`DocContent::place`], [`DocContent::add_tree`]
242/// and [`DocContent::resolve`] build it tree by tree; [`Doc::new`] and
243/// [`Doc::with_options`] make a document of it.
244#[derive(Default)]
245pub struct DocContent {
246    arena: Vec<Arc<Fragment>>,
247    traversal: Vec<TreeId>,
248    resolution: BTreeMap<NodeAddr, TreeId>,
249    placed: BTreeMap<TreeId, NodeAddr>,
250}
251
252impl DocContent {
253    /// Content with no tree.
254    pub fn new() -> DocContent {
255        DocContent::default()
256    }
257
258    /// Adds a tree for `fragment` to the arena and appends it to the traversal
259    /// list, so that the walk visits it after the trees listed before it;
260    /// returns the tree's [`TreeId`].
261    ///
262    /// The same `Arc<Fragment>` added twice gives two distinct trees with
263    /// separate computed data, because each tree is a separate placement in the
264    /// document.
265    ///
266    /// See [`DocContent::add_tree`] for a tree that the walk reaches through a
267    /// node that places it, rather than through the traversal list.
268    ///
269    /// # Panics
270    ///
271    /// Panics under the same condition as [`DocContent::add_tree`].
272    ///
273    /// # Examples
274    ///
275    /// ```
276    /// use std::sync::Arc;
277    ///
278    /// use flm_core::model::doc::{DocContent, Fragment, FragmentLayout};
279    /// use flm_core::lang::{
280    ///     build_language, parse_fragment, FlmOrigin, LangInputs, ParseOptions,
281    /// };
282    /// use flm_core::techy::source::Source;
283    ///
284    /// let lang = build_language(LangInputs::new());
285    /// let source = Arc::new(Source::new("hello").with_origin(FlmOrigin::none()));
286    /// let fragment = parse_fragment(
287    ///     &lang,
288    ///     source,
289    ///     FragmentLayout::default(),
290    ///     &ParseOptions::default(),
291    /// )?;
292    ///
293    /// let mut content = DocContent::new();
294    /// let shared = Arc::new(fragment);
295    /// let first = content.place(Arc::clone(&shared));
296    /// let second = content.place(shared);
297    /// assert_ne!(first, second);
298    /// assert_eq!(content.walk_trees().collect::<Vec<_>>(), [first, second]);
299    /// # Ok::<(), flm_core::lang::FragmentError>(())
300    /// ```
301    pub fn place(&mut self, fragment: Arc<Fragment>) -> TreeId {
302        let id = self.add_tree(fragment);
303        self.traversal.push(id);
304        id
305    }
306
307    /// Adds a tree for `fragment` to the arena without appending it to the
308    /// traversal list; returns the tree's [`TreeId`].
309    ///
310    /// Use this for a tree that the walk is to reach through a node that places
311    /// it ([`DocContent::resolve`]). A tree that is neither listed nor placed
312    /// is part of the document but is never walked.
313    ///
314    /// # Panics
315    ///
316    /// Panics if the arena already holds 2³¹ trees, the largest number of
317    /// trees a [`TreeId`] can tell apart from synthesized values.
318    pub fn add_tree(&mut self, fragment: Arc<Fragment>) -> TreeId {
319        // The bound is `TreeId::tree`'s own (the tag bit): checked here so the
320        // message names the real limit.
321        let index = u32::try_from(self.arena.len())
322            .ok()
323            .filter(|index| index >> 31 == 0)
324            .expect("a document holds fewer than 2^31 trees");
325        self.arena.push(fragment);
326        TreeId::tree(index)
327    }
328
329    /// Records that the node `site` places the tree `target`: the walk enters
330    /// `target` right after it reaches `site`.
331    ///
332    /// `site` is an address in a tree **as parsed**. Several runs with
333    /// different rewrites may share one document, and a rewrite produces a new
334    /// tree with new node identifiers, so an address taken after the rewrites
335    /// would hold for one run at most; the resolution map of a document
336    /// therefore uses the node identifiers that the parse produced.
337    ///
338    /// [`assemble`](crate::model::assemble::assemble) places the tree of every
339    /// included file that opens with a heading at the node of its `\input`
340    /// command. A program that embeds the library may also use this to build a
341    /// document from several fragments.
342    ///
343    /// # Errors
344    ///
345    /// Returns a [`PlacementError`], and records nothing, when `target` or
346    /// `site.tree` is not a tree of this document
347    /// ([`UnknownTree`](PlacementError::UnknownTree)), when `site` belongs to
348    /// `target` itself ([`SelfPlacement`](PlacementError::SelfPlacement)),
349    /// when another node already places `target`
350    /// ([`AlreadyPlaced`](PlacementError::AlreadyPlaced)), or when `site`
351    /// already places a tree ([`SiteTaken`](PlacementError::SiteTaken)).
352    pub fn resolve(&mut self, site: NodeAddr, target: TreeId) -> Result<(), PlacementError> {
353        if self.fragment(target).is_none() {
354            return Err(PlacementError::UnknownTree(target));
355        }
356        if self.fragment(site.tree).is_none() {
357            return Err(PlacementError::UnknownTree(site.tree));
358        }
359        if site.tree == target {
360            return Err(PlacementError::SelfPlacement(target));
361        }
362        if let Some(&first) = self.placed.get(&target) {
363            return Err(PlacementError::AlreadyPlaced { target, first, second: site });
364        }
365        if let Some(&existing) = self.resolution.get(&site) {
366            return Err(PlacementError::SiteTaken { site, target: existing });
367        }
368        self.resolution.insert(site, target);
369        self.placed.insert(target, site);
370        Ok(())
371    }
372
373    /// The fragment of the tree `tree` of this document.
374    ///
375    /// Returns `None` when `tree` identifies a synthesized value or its index
376    /// is past the end of the arena.
377    pub fn fragment(&self, tree: TreeId) -> Option<&Arc<Fragment>> {
378        if tree.is_value() {
379            return None;
380        }
381        self.arena.get(tree.index() as usize)
382    }
383
384    /// The node tree of the tree `tree` of this document: the tree of its
385    /// [`fragment`](DocContent::fragment).
386    ///
387    /// Returns `None` under the same conditions as
388    /// [`DocContent::fragment`].
389    pub fn tree(&self, tree: TreeId) -> Option<&Arc<NodeTree<Flm>>> {
390        self.fragment(tree).map(|fragment| fragment.tree())
391    }
392
393    /// Every tree of the arena with its fragment, in the order the trees were
394    /// added. This is not document order; [`DocContent::walk_trees`] gives
395    /// the trees in document order.
396    pub fn trees(&self) -> impl Iterator<Item = (TreeId, &Arc<Fragment>)> + '_ {
397        self.arena
398            .iter()
399            .enumerate()
400            .map(|(index, fragment)| (TreeId::tree(index as u32), fragment))
401    }
402
403    /// The number of trees in the arena, walked or not.
404    pub fn len(&self) -> usize {
405        self.arena.len()
406    }
407
408    /// Returns `true` when the arena holds no tree.
409    pub fn is_empty(&self) -> bool {
410        self.arena.is_empty()
411    }
412
413    /// The traversal list: the trees the walk visits in their own right, in
414    /// order. A tree that the walk reaches only through a node that places it
415    /// is not in this list.
416    pub fn traversal(&self) -> &[TreeId] {
417        &self.traversal
418    }
419
420    /// The resolution map: for each node that places a tree, the tree it
421    /// places. The keys are addresses in the trees as parsed.
422    pub fn resolution(&self) -> &BTreeMap<NodeAddr, TreeId> {
423        &self.resolution
424    }
425
426    /// The tree that the node `site` places, or `None` when it places none.
427    pub fn placement_of(&self, site: NodeAddr) -> Option<TreeId> {
428        self.resolution.get(&site).copied()
429    }
430
431    /// The node that places the tree `target`, or `None` when no node places
432    /// it.
433    pub fn placed_at(&self, target: TreeId) -> Option<NodeAddr> {
434        self.placed.get(&target).copied()
435    }
436
437    /// The walk over the trees as parsed: the steps of the traversal in
438    /// document order.
439    ///
440    /// The iterator yields a [`WalkStep`] when it enters a tree and when it
441    /// leaves it, and one for every node in between, in pre-order (a node
442    /// before its children), with the node's address. This is the library's
443    /// definition of document order; see the [module
444    /// documentation](self#the-walk) for what that order is.
445    ///
446    /// [`DocContent::walk_nodes`] and [`DocContent::walk_trees`] give the
447    /// nodes alone and the trees alone.
448    pub fn walk(&self) -> Walk<'_> {
449        Walk::new(self)
450    }
451
452    /// The nodes of the walk: every node of every walked tree, in document
453    /// order, with its address.
454    pub fn walk_nodes(&self) -> impl Iterator<Item = (NodeAddr, NodeRef<'_, Flm>)> + '_ {
455        self.walk().filter_map(|step| match step {
456            WalkStep::Node(addr, node) => Some((addr, node)),
457            _ => None,
458        })
459    }
460
461    /// The trees of the walk, in document order, each once.
462    pub fn walk_trees(&self) -> impl Iterator<Item = TreeId> + '_ {
463        self.walk().filter_map(|step| match step {
464            WalkStep::EnterTree(tree) => Some(tree),
465            _ => None,
466        })
467    }
468}
469
470/// The content of a document is the walk's source for its trees as parsed: the
471/// arena gives the trees, the traversal list the trees listed, and the
472/// resolution map the placements.
473impl WalkSource for DocContent {
474    fn listed(&self) -> &[TreeId] {
475        &self.traversal
476    }
477
478    fn node_tree(&self, tree: TreeId) -> Option<&NodeTree<Flm>> {
479        self.tree(tree).map(|tree| &**tree)
480    }
481
482    fn placement(&self, site: NodeAddr) -> Option<TreeId> {
483        self.placement_of(site)
484    }
485}
486
487impl fmt::Debug for DocContent {
488    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
489        f.debug_struct("DocContent")
490            .field("arena", &self.arena)
491            .field("traversal", &self.traversal)
492            .field("resolution", &self.resolution)
493            .finish()
494    }
495}
496
497/// The trees a [`Walk`] visits: trees by identifier, the trees of the
498/// traversal list in order, and which node places which tree.
499///
500/// [`Walk`] defines document order and reads its trees through this trait, so
501/// that the same order applies to any set of trees that represents a
502/// document's trees: [`DocContent`] is the source of the trees as parsed, and a
503/// run is the source of its frozen trees, what each tree became after the
504/// rewrites ([`StageCx::walk`](crate::core::run::StageCx::walk)). The [module
505/// documentation](self#the-walk) describes the order.
506pub trait WalkSource {
507    /// The trees of the traversal list, in the order the walk visits them. A
508    /// tree that the walk reaches only through a node that places it is not in
509    /// this list.
510    fn listed(&self) -> &[TreeId];
511
512    /// The node tree of the tree `tree`, or `None` when the source holds no
513    /// tree with that identifier; the walk then does not enter it.
514    fn node_tree(&self, tree: TreeId) -> Option<&NodeTree<Flm>>;
515
516    /// The tree that the node at `site`, a node of one of the source's trees,
517    /// places, or `None` when it places none.
518    fn placement(&self, site: NodeAddr) -> Option<TreeId>;
519}
520
521/// One step of the walk, yielded by [`Walk`].
522pub enum WalkStep<'d> {
523    /// The walk enters a tree, either at its position in the traversal list or
524    /// right after the node that places it. Every step until the matching
525    /// [`WalkStep::ExitTree`] belongs to that tree or to a tree placed in it.
526    EnterTree(TreeId),
527    /// A node, with its address. The nodes of one tree come in pre-order: a
528    /// node before its children.
529    Node(NodeAddr, NodeRef<'d, Flm>),
530    /// The walk leaves a tree; every node of it has been yielded.
531    ExitTree(TreeId),
532}
533
534impl fmt::Debug for WalkStep<'_> {
535    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
536        match self {
537            WalkStep::EnterTree(tree) => write!(f, "EnterTree({tree})"),
538            WalkStep::Node(addr, node) => write!(f, "Node({addr:?}, {})", node.summary()),
539            WalkStep::ExitTree(tree) => write!(f, "ExitTree({tree})"),
540        }
541    }
542}
543
544/// One open tree of the walk.
545struct WalkFrame<'d> {
546    tree: TreeId,
547    root: Option<NodeRef<'d, Flm>>,
548    descendants: Descendants<'d, Flm>,
549}
550
551/// The walk: an iterator over the steps of the traversal of a [`WalkSource`]
552/// in document order.
553///
554/// [`DocContent::walk`] returns one for the trees as parsed; [`Walk::new`]
555/// creates one over any other source. A tree that the source lists twice, or
556/// that is both listed and placed, is entered once only, the first time the
557/// walk reaches it.
558pub struct Walk<'d, S: ?Sized = DocContent> {
559    source: &'d S,
560    list_index: usize,
561    stack: Vec<WalkFrame<'d>>,
562    /// Whether each tree was entered, by the tree's index.
563    visited: Vec<bool>,
564    /// A tree whose entry step is due next: the placing node was just yielded.
565    pending: Option<(TreeId, &'d NodeTree<Flm>)>,
566}
567
568impl<'d, S: WalkSource + ?Sized> Walk<'d, S> {
569    /// The walk over the trees of `source`, starting from the first tree of its
570    /// traversal list.
571    pub fn new(source: &'d S) -> Walk<'d, S> {
572        Walk { source, list_index: 0, stack: Vec::new(), visited: Vec::new(), pending: None }
573    }
574
575    /// Whether the walk has entered the tree `tree`.
576    fn visited(&self, tree: TreeId) -> bool {
577        self.visited.get(tree.index() as usize).copied().unwrap_or(false)
578    }
579
580    fn enter(&mut self, tree: TreeId, nodes: &'d NodeTree<Flm>) -> WalkStep<'d> {
581        let index = tree.index() as usize;
582        if self.visited.len() <= index {
583            self.visited.resize(index + 1, false);
584        }
585        self.visited[index] = true;
586        let root = nodes.root();
587        self.stack.push(WalkFrame { tree, root: Some(root), descendants: root.descendants() });
588        WalkStep::EnterTree(tree)
589    }
590}
591
592impl<'d, S: WalkSource + ?Sized> Iterator for Walk<'d, S> {
593    type Item = WalkStep<'d>;
594
595    fn next(&mut self) -> Option<WalkStep<'d>> {
596        if let Some((tree, nodes)) = self.pending.take() {
597            return Some(self.enter(tree, nodes));
598        }
599        let source = self.source;
600        if let Some(frame) = self.stack.last_mut() {
601            let next = frame.root.take().or_else(|| frame.descendants.next());
602            return match next {
603                Some(node) => {
604                    let addr = NodeAddr::new(frame.tree, node.id());
605                    if let Some(target) = source.placement(addr) {
606                        if !self.visited(target) {
607                            // The placed tree follows its placing node: its entry
608                            // step is the next one yielded, then its nodes, then
609                            // the rest of this tree.
610                            self.pending = source.node_tree(target).map(|nodes| (target, nodes));
611                        }
612                    }
613                    Some(WalkStep::Node(addr, node))
614                }
615                None => {
616                    let frame = self.stack.pop().expect("a frame was just observed");
617                    Some(WalkStep::ExitTree(frame.tree))
618                }
619            };
620        }
621        // Between listed trees: the next not-yet-visited listed tree the
622        // source holds.
623        let listed = source.listed();
624        while self.list_index < listed.len() {
625            let tree = listed[self.list_index];
626            self.list_index += 1;
627            if self.visited(tree) {
628                continue;
629            }
630            if let Some(nodes) = source.node_tree(tree) {
631                return Some(self.enter(tree, nodes));
632            }
633        }
634        None
635    }
636}
637
638/// A document: its [content](DocContent) together with the option values set
639/// on it.
640///
641/// A `Doc` does not change once built, and several runs may share one, for
642/// example to render the same document in two formats, or to check it and then
643/// render it. What a run computes (tables of data, the diagnostics of its
644/// stages) is kept by that run, not here. A run is constructed over a document
645/// with [`Run::new`](crate::core::run::Run::new).
646#[derive(Debug, Default)]
647pub struct Doc {
648    content: DocContent,
649    options: OptionValues,
650}
651
652impl Doc {
653    /// A document holding `content`, with no option value set on it. A stage
654    /// then reads, for each option type, the value set on the render request,
655    /// or else the type's default.
656    pub fn new(content: DocContent) -> Doc {
657        Doc { content, options: OptionValues::new() }
658    }
659
660    /// A document holding `content`, with the option values `options` set on
661    /// it.
662    ///
663    /// The values are not checked here. Constructing a run over this document
664    /// ([`Run::new`](crate::core::run::Run::new)) checks them against the
665    /// option types the registry declares, and fails with
666    /// [`RunError::DocumentOption`](crate::core::run::RunError::DocumentOption)
667    /// when a value is set for an option type that no feature declares or that
668    /// cannot be set on a document. See [`crate::model::options`].
669    pub fn with_options(content: DocContent, options: OptionValues) -> Doc {
670        Doc { content, options }
671    }
672
673    /// The document's content: its trees, their order, and which node places
674    /// which tree.
675    pub fn content(&self) -> &DocContent {
676        &self.content
677    }
678
679    /// The option values set on this document.
680    pub fn options(&self) -> &OptionValues {
681        &self.options
682    }
683}