Skip to main content

flm_core/core/run/
order.rs

1//! The run's document order: the document's walk applied to the run's frozen
2//! trees, computed once when the rewrite stages are over.
3//!
4//! Document order is defined once, by the document's walk
5//! ([`DocContent::walk`](crate::model::doc::DocContent::walk)): the listed trees
6//! in order, each tree entered once, and a placed tree (the tree of an included
7//! file that opens with a heading) entered at the node that places it, its nodes
8//! following that node immediately and coming before the node's own children.
9//! The rewrite stages produce new trees, with new node identities, so the run
10//! applies the walk to the frozen trees, the trees as the last rewrite stage
11//! left them, and records three things:
12//!
13//! - **the placements of the run's trees**: which node of a frozen tree places
14//!   which tree. The document records each placement by the placing node as
15//!   parsed; the run finds that node again in the frozen tree by the source
16//!   span it was written at, which every rewrite stage keeps;
17//! - **the run's order of the trees**: the order in which the walk enters them;
18//! - **the walk itself**: every node of those trees in document order, and each
19//!   node's position in it ([`DocPosition`]).
20//!
21//! The run's trees are the trees that the walk reaches. A tree that the walk
22//! does not reach is not a tree of the run: no later stage reads it and no
23//! output contains it, and its content is dropped together with the node that
24//! placed it. This happens when a rewrite stage removed the placing node (for
25//! example, a user definition whose template does not use the argument that
26//! held the `\input`), or when the tree that includes it failed its rewrite.
27//!
28//! A rewrite stage may also copy a placing node, so that it appears at two
29//! places of the frozen trees. The first copy in document order then places the
30//! tree, and the run reports [`PlacedTwice`] at every other copy.
31//!
32//! A stage reads this order through its context: [`StageCx::walk`],
33//! [`StageCx::trees`], [`StageCx::position`] and [`StageCx::placement_of`]. An
34//! embedding program reads the run's order of the trees with
35//! [`Run::tree_order`].
36//!
37//! [`StageCx::walk`]: crate::core::run::StageCx::walk
38//! [`StageCx::trees`]: crate::core::run::StageCx::trees
39//! [`StageCx::position`]: crate::core::run::StageCx::position
40//! [`StageCx::placement_of`]: crate::core::run::StageCx::placement_of
41//! [`Run::tree_order`]: crate::core::run::Run::tree_order
42
43// The walk is not implemented here: the run is a `WalkSource` for its frozen
44// trees and the placements it found again, and `Walk` walks it as it walks the
45// document's trees as parsed; the run records the steps.
46
47use std::collections::BTreeMap;
48use std::sync::Arc;
49
50use techy::core::node::NodeTree;
51use techy::error::{Diagnostic, DiagnosticInfo};
52
53use crate::lang::input::is_placing;
54use crate::lang::{Flm, FlmDiagnostics};
55use crate::model::addr::{NodeAddr, TreeId};
56use crate::model::doc::{DocContent, Walk, WalkSource, WalkStep};
57
58/// A node's position in the run's document order: of two nodes of the run's
59/// trees, the one with the smaller position comes first in the document.
60///
61/// Positions compare nodes of one run only and mean nothing outside it.
62/// [`StageCx::position`](crate::core::run::StageCx::position) returns the
63/// position of a node of a frozen tree; a document-scope stage (a stage of
64/// [`Scope::Document`](crate::core::stage::Scope::Document), run once for the
65/// whole document) that gathers nodes from several trees sorts them by
66/// position to put them in document order.
67#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
68pub struct DocPosition(usize);
69
70/// Diagnostic condition `flm.run.placed-twice`, reported at Error severity: a
71/// node that places a tree of the document appears at two places of the run's
72/// trees, because a rewrite stage copied it.
73///
74/// This happens when a user definition's template writes twice the argument
75/// that holds the `\input` of a file that opens with a heading. A tree is
76/// placed by one node only: the first copy in document order places it, and
77/// the run reports this condition at each other copy, which places nothing.
78#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
79#[diagnostic(
80    id = "flm.run.placed-twice",
81    message = "a file that opens with a heading can be included only once: `{file}` is \
82               included here a second time, because a macro or environment definition uses the \
83               argument that holds its `\\input` more than once"
84)]
85pub struct PlacedTwice {
86    /// The canonical path of the placed tree's file, or the tree's identifier
87    /// when its source has no file path.
88    pub file: String,
89}
90
91/// The run's document order. See the [module documentation](self).
92#[derive(Debug, Default)]
93pub(crate) struct RunOrder {
94    /// The tree each placing node of the run's trees places, by the node's
95    /// address in its frozen tree.
96    placements: BTreeMap<NodeAddr, TreeId>,
97    /// The trees in the order the walk enters them.
98    trees: Vec<TreeId>,
99    /// Every node of `trees`, in document order.
100    walk: Vec<NodeAddr>,
101    /// For each tree, the position in `walk` of each node, by the node's index
102    /// in its tree's storage; `usize::MAX` for a node the walk does not visit.
103    positions: BTreeMap<TreeId, Vec<usize>>,
104}
105
106/// The run's trees as the walk's source: the document's listed trees, the
107/// frozen trees, and the placements the run found again in them.
108struct FrozenSource<'a> {
109    listed: &'a [TreeId],
110    frozen: &'a BTreeMap<TreeId, Arc<NodeTree<Flm>>>,
111    placements: &'a BTreeMap<NodeAddr, TreeId>,
112}
113
114impl WalkSource for FrozenSource<'_> {
115    fn listed(&self) -> &[TreeId] {
116        self.listed
117    }
118
119    fn node_tree(&self, tree: TreeId) -> Option<&NodeTree<Flm>> {
120        self.frozen.get(&tree).map(|tree| &**tree)
121    }
122
123    fn placement(&self, site: NodeAddr) -> Option<TreeId> {
124        self.placements.get(&site).copied()
125    }
126}
127
128impl RunOrder {
129    /// The order of the frozen trees `frozen` of the document `content`, and
130    /// the diagnostics of a tree placed twice.
131    pub(crate) fn new(
132        content: &DocContent,
133        frozen: &BTreeMap<TreeId, Arc<NodeTree<Flm>>>,
134    ) -> (RunOrder, FlmDiagnostics) {
135        let mut diags = FlmDiagnostics::new();
136        let placements = placements(content, frozen, &mut diags);
137        let source = FrozenSource { listed: content.traversal(), frozen, placements: &placements };
138        let mut trees = Vec::new();
139        let mut walk = Vec::new();
140        let mut positions: BTreeMap<TreeId, Vec<usize>> = BTreeMap::new();
141        for step in Walk::new(&source) {
142            match step {
143                WalkStep::EnterTree(tree) => {
144                    trees.push(tree);
145                    positions.insert(tree, vec![usize::MAX; frozen[&tree].node_count()]);
146                }
147                WalkStep::Node(addr, _) => {
148                    if let Some(slot) =
149                        positions.get_mut(&addr.tree).and_then(|p| p.get_mut(addr.node.index()))
150                    {
151                        *slot = walk.len();
152                    }
153                    walk.push(addr);
154                }
155                WalkStep::ExitTree(_) => {}
156            }
157        }
158        (RunOrder { placements, trees, walk, positions }, diags)
159    }
160
161    /// Whether the walk reaches the tree `tree`, that is whether it is a tree
162    /// of the run.
163    pub(crate) fn has_tree(&self, tree: TreeId) -> bool {
164        self.positions.contains_key(&tree)
165    }
166
167    /// The trees in the order the walk enters them.
168    pub(crate) fn trees(&self) -> &[TreeId] {
169        &self.trees
170    }
171
172    /// Every node of the run's trees, in document order.
173    pub(crate) fn walk(&self) -> &[NodeAddr] {
174        &self.walk
175    }
176
177    /// The position of a node of the run's trees in document order, or `None`
178    /// for a node the walk does not visit.
179    pub(crate) fn position(&self, addr: NodeAddr) -> Option<DocPosition> {
180        let position = *self.positions.get(&addr.tree)?.get(addr.node.index())?;
181        (position != usize::MAX).then_some(DocPosition(position))
182    }
183
184    /// The tree a node of the run's trees places, if it places one.
185    pub(crate) fn placement_of(&self, addr: NodeAddr) -> Option<TreeId> {
186        self.placements.get(&addr).copied()
187    }
188}
189
190/// The placements of the run's trees: for each placement of the document, the
191/// node of the frozen tree that places the tree — a placing node written at
192/// the same place as the placing node as parsed. A second such node is
193/// reported, and places nothing.
194fn placements(
195    content: &DocContent,
196    frozen: &BTreeMap<TreeId, Arc<NodeTree<Flm>>>,
197    diags: &mut FlmDiagnostics,
198) -> BTreeMap<NodeAddr, TreeId> {
199    // The placing nodes of each frozen tree that places anything, in the order
200    // they are written.
201    let mut placing: BTreeMap<TreeId, Vec<NodeAddr>> = BTreeMap::new();
202    for site in content.resolution().keys() {
203        let Some(tree) = frozen.get(&site.tree) else { continue };
204        placing.entry(site.tree).or_insert_with(|| {
205            let root = tree.root();
206            std::iter::once(root)
207                .chain(root.descendants())
208                .filter(is_placing)
209                .map(|node| NodeAddr::new(site.tree, node.id()))
210                .collect()
211        });
212    }
213    let mut found = BTreeMap::new();
214    for (site, target) in content.resolution() {
215        let Some(parsed) = content.tree(site.tree).and_then(|tree| tree.get(site.node)) else {
216            continue;
217        };
218        let (Some(tree), Some(candidates)) = (frozen.get(&site.tree), placing.get(&site.tree))
219        else {
220            continue;
221        };
222        // A placing node is found by its span: every rewrite keeps a copied
223        // node's span, and two distinct commands never share one, so the node
224        // needs no identifier of its own. A template that writes the command
225        // twice makes several copies, the later ones reported below.
226        let mut copies = candidates.iter().filter_map(|addr| {
227            let node = tree.get(addr.node)?;
228            (node.span() == parsed.span()).then_some((*addr, node))
229        });
230        let Some((first, _)) = copies.next() else { continue };
231        found.insert(first, *target);
232        for (_, node) in copies {
233            let file = content
234                .fragment(*target)
235                .and_then(|fragment| fragment.source().origin().canonical_path().map(String::from))
236                .unwrap_or_else(|| target.to_string());
237            diags.push(Diagnostic::error(PlacedTwice { file }, node.span().clone()));
238        }
239    }
240    found
241}