Skip to main content

flm_core/stdlib/backends/lowering/
table.rs

1//! The lowered-trees table, into which a backend's lowering stage writes its
2//! result, and the address of a node inside a lowered tree.
3//!
4//! A **table** is typed data that one stage writes beside the frozen trees and
5//! other stages read; its identity is its registered dotted name, and that
6//! name is also a capability ([`Table`]; see [frozen trees and computed
7//! data](crate::guide::concepts_overview#frozen-trees-and-computed-data)).
8//!
9//! Every backend uses the table type of this module, [`LoweredTrees`],
10//! with an instance of its own named `flm.lowered.<backend>`
11//! ([`lowered_table_name`], [`lowered_table`]). For each document tree, the
12//! table holds the lowered tree ([`LoweredTree`]), the identifiers of the
13//! definitions its rules required (style and script definitions on HTML,
14//! package requests and definition pieces on LaTeX), and how many rounds
15//! lowering ran. [`LoweredAddr`] is the address of one node inside a lowered
16//! tree; the text backend's position marks use it.
17
18use std::collections::{BTreeMap, BTreeSet};
19use std::fmt;
20use std::sync::Arc;
21
22use techy::core::node::{NodeRef, NodeTree};
23use techy::serialize::SerialValue;
24
25use crate::model::addr::{NodeId, TreeId};
26use crate::model::names::{BackendName, CapName, Name};
27use crate::core::data::table::{ProjectCx, Table, TableHandle};
28use crate::lang::Flm;
29
30/// The address of a node of a *lowered* tree: the document tree it was
31/// lowered from, and the node's position in that tree's lowered form (its
32/// index in storage order).
33///
34/// It is not a [`NodeAddr`](crate::model::addr::NodeAddr), which identifies a
35/// node of a *frozen* tree, for two reasons. A lowered node may have no
36/// frozen counterpart: a rule may synthesize nodes that represent no single
37/// frozen node, and a lowered tree stores no map back to the frozen one. And
38/// the node identifiers techy assigns carry a per-tree tag that differs from
39/// run to run, whereas a position is the same in two runs over the same
40/// document. An address is looked up in the lowered-trees table with
41/// [`resolve`](LoweredAddr::resolve). The text backend's position marks
42/// ([`TextMark::addr`](crate::stdlib::backends::text::TextMark::addr)) are
43/// addresses of this kind.
44///
45/// # Examples
46///
47/// ```
48/// use flm_core::model::addr::TreeId;
49/// use flm_core::stdlib::backends::lowering::LoweredAddr;
50///
51/// let addr = LoweredAddr::at(TreeId::tree(0), 5);
52/// assert_eq!(addr.to_string(), "tree#0/5");
53/// ```
54#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
55pub struct LoweredAddr {
56    /// The document tree whose lowered form holds the node.
57    pub tree: TreeId,
58    /// The node's index in the lowered tree's storage order.
59    pub index: u32,
60}
61
62impl LoweredAddr {
63    /// The address of the node `node` in the lowered form of the document tree
64    /// `tree`.
65    ///
66    /// `node` must be a node of that lowered tree. Nothing checks it here: an
67    /// identifier from another tree gives the address of a different
68    /// position.
69    pub fn new(tree: TreeId, node: NodeId) -> LoweredAddr {
70        LoweredAddr { tree, index: node.index() as u32 }
71    }
72
73    /// The address of the node at `index` in storage order in the lowered form
74    /// of the document tree `tree`.
75    pub const fn at(tree: TreeId, index: u32) -> LoweredAddr {
76        LoweredAddr { tree, index }
77    }
78
79    /// The node at this address, looked up in `trees`.
80    ///
81    /// Returns `None` when `trees` holds no lowered form of this address's
82    /// document tree (its lowering failed, or the backend never lowered it), or
83    /// when that lowered tree has no node at this position.
84    pub fn resolve<'t>(&self, trees: &'t LoweredTrees) -> Option<NodeRef<'t, Flm>> {
85        trees.get(self.tree)?.tree.iter_storage_order().nth(self.index as usize)
86    }
87}
88
89impl fmt::Display for LoweredAddr {
90    /// `tree#0/5`: the tree, then the index.
91    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92        write!(f, "{}/{}", self.tree, self.index)
93    }
94}
95
96/// The lowered form of one document tree: the tree an emitter walks, the
97/// requirements its rules recorded, and how many rounds lowering took.
98#[derive(Debug, Clone)]
99pub struct LoweredTree {
100    /// The lowered tree.
101    pub tree: Arc<NodeTree<Flm>>,
102    /// The requirements of this tree: the identifiers of the definitions its
103    /// output needs (style and script definitions on HTML, package requests
104    /// and definition pieces on LaTeX; see [style and script
105    /// definitions](crate::guide::concepts_overview#style-and-script-definitions)).
106    /// Two sets, merged: what the selected rules require whenever they are
107    /// selected
108    /// ([`LoweringDecl::selection_requires`](crate::core::lowering::LoweringDecl::selection_requires),
109    /// the same for every lowered tree of one plan), and what the rules
110    /// recorded at their nodes in this tree, through
111    /// [`Lowerer::require`](crate::core::lowering::Lowerer::require). The
112    /// backend that writes the output resolves them.
113    pub requires: BTreeSet<Name>,
114    /// How many rounds ran over this tree; at least one. See
115    /// [`lower_tree`](super::lower_tree).
116    pub rounds: u32,
117}
118
119/// The lowered trees of one backend, keyed by the document tree each was
120/// lowered from — the table `flm.lowered.<backend>`.
121///
122/// The backend's lowering stage ([`LoweringStage`](super::LoweringStage))
123/// writes it, and the backend's emit stage reads it. A tree whose lowering
124/// failed has no entry here; the failure is reported as an Error diagnostic
125/// instead ([`super::error`]). The table's projection lists `{tree, rounds,
126/// requires}` per entry, not the lowered trees themselves: a consumer that
127/// needs them projects them itself ([`crate::dump::project`]).
128#[derive(Debug, Clone, Default)]
129pub struct LoweredTrees {
130    /// Document tree → its lowered form.
131    pub trees: BTreeMap<TreeId, LoweredTree>,
132}
133
134impl LoweredTrees {
135    /// The lowered form of the document tree `id`, or `None` when the backend
136    /// has none for it.
137    pub fn get(&self, id: TreeId) -> Option<&LoweredTree> {
138        self.trees.get(&id)
139    }
140}
141
142impl Table for LoweredTrees {
143    fn absorb(&mut self, piece: LoweredTrees) {
144        self.trees.extend(piece.trees);
145    }
146
147    fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
148        SerialValue::List(
149            self.trees
150                .iter()
151                .map(|(id, lowered)| {
152                    SerialValue::Map(vec![
153                        (String::from("tree"), cx.tree_ref(*id)),
154                        (String::from("rounds"), SerialValue::Int(i64::from(lowered.rounds))),
155                        (
156                            String::from("requires"),
157                            SerialValue::List(
158                                lowered
159                                    .requires
160                                    .iter()
161                                    .map(|name| SerialValue::Str(name.to_string()))
162                                    .collect(),
163                            ),
164                        ),
165                    ])
166                })
167                .collect(),
168        )
169    }
170}
171
172/// The name of `backend`'s lowered-trees table, `flm.lowered.<backend>` — both
173/// the table's name and the capability that writing it provides.
174///
175/// # Examples
176///
177/// ```
178/// use flm_core::stdlib::backends::lowering::lowered_table_name;
179///
180/// assert_eq!(lowered_table_name(&"text".into()).as_str(), "flm.lowered.text");
181/// ```
182pub fn lowered_table_name(backend: &BackendName) -> CapName {
183    CapName::from(format!("flm.lowered.{backend}"))
184}
185
186/// The typed handle through which a stage reads or writes `backend`'s
187/// lowered trees.
188///
189/// The feature that registers the backend must have declared the table under
190/// the name [`lowered_table_name`] returns; a handle alone does not create
191/// it.
192pub fn lowered_table(backend: &BackendName) -> TableHandle<LoweredTrees> {
193    TableHandle::new(lowered_table_name(backend))
194}