flm_core/core/run/cx.rs
1//! The contexts through which a stage and a rewrite stage read what they need
2//! during one call, and value catch-up, which brings a synthesized value up to
3//! date.
4//!
5//! The runner creates a [`StageCx`] for each call of a stage that runs after the
6//! trees are frozen, and a [`RewriteCx`] for each call of a rewrite stage
7//! ([`RewriteStage`](crate::core::stage::RewriteStage)), which runs before. Each
8//! context exists only for that one call.
9//!
10//! # What a stage reads through its context
11//!
12//! A stage context ([`StageCx`]) gives a stage, during one call:
13//!
14//! - the document, the registry and the plan;
15//! - the **frozen trees**. A frozen tree is a document tree after the rewrite
16//! stages have run: it is never changed again, and everything a later stage
17//! computes about it is stored in tables beside it, keyed by node address
18//! ([frozen trees and computed
19//! data](crate::guide::concepts_overview#frozen-trees-and-computed-data)).
20//! [`StageCx::tree`] returns one by identifier; a tree whose rewrite failed
21//! has no frozen tree. A stage receives the frozen trees through its
22//! context, not by reading the rewrite stages' tables;
23//! - the **run's document order**, the document's walk applied to the frozen
24//! trees ([`crate::core::run::order`]): [`StageCx::walk`] visits the nodes in
25//! that order, [`StageCx::position`] returns a node's position in it, and
26//! [`StageCx::placement_of`] the tree that a node places;
27//! - the tables the stage declared as reads, through a view that refuses a read
28//! the stage did not declare ([`StageCx::get`]);
29//! - the values of the option types the stage declared, resolved once for the
30//! run: the value set on the plan request, else the value set on the
31//! document, else the type's default ([`StageCx::option`]);
32//! - the services the registry holds ([`StageCx::service`]);
33//! - node addresses, by which computed data is keyed ([`StageCx::addr`]);
34//! - value catch-up ([`StageCx::resolve_value`]), described below;
35//! - the [`Scope`](crate::progress::Scope) of the stage's row on the progress
36//! sheet ([`StageCx::progress`]), under which the stage declares the rows of
37//! its own slow work and asks whether the build was cancelled.
38//!
39//! A stage writes nothing through its context: it writes what it produces into
40//! the [`StageOut`] that it receives together with the context.
41//!
42//! A rewrite stage reads much less through its [`RewriteCx`]: the identifier and
43//! the layout of the tree being rewritten, the registry, and the option types
44//! it declared. A `RewriteCx` gives no access to any table, so the rule that a
45//! rewrite stage reads no computed data is enforced by the types.
46//!
47//! # Value catch-up
48//!
49//! A synthesized value is a small tree that a stage builds while a run is under
50//! way, held outside the document's trees and numbered per stage invocation; a
51//! consumer brings it up to date through value catch-up before reading it as
52//! document content ([synthesized
53//! values](crate::guide::concepts_overview#synthesized-values)). An example is
54//! the content that a stage assembles from a user definition's template and
55//! stores in a table. No rewrite stage has run over a synthesized value, and no
56//! stage has computed anything about it.
57//!
58//! [Value catch-up](crate::guide::concepts_overview#value-catch-up) does that
59//! work when something comes to render the synthesized value:
60//! [`StageCx::resolve_value`] runs the plan's rewrite stages over it, then the
61//! per-tree stages (stages of [`Scope::PerTree`], run once for each tree) that
62//! the consumer depends on, over the synthesized value
63//! alone. What these stages compute goes into a catch-up store that belongs to
64//! that one catch-up and is returned in [`CaughtUp`]; the run's store is never
65//! written. Stages that run once for the whole document are not run again, and
66//! a table piece that states a fact about the document as a whole is refused
67//! ([`PieceClass`](crate::core::data::table::PieceClass)).
68//!
69//! A table that the catch-up store holds is read whole from it, never entry by
70//! entry. A feature author must know the consequence, which
71//! [`ComputedView::with_overlay`] states. Reading one table from both stores at
72//! once would need a merged copy of a type-erased table, which the
73//! [`Table`](crate::core::data::table::Table) trait does not offer, and it would
74//! weaken the rule that keeps a synthesized value from stating a fact about the
75//! document.
76//!
77//! The diagnostics that the stages report during value catch-up are returned in
78//! [`CaughtUp`], every one of them: a stage reports over a synthesized value
79//! exactly as it does over a document tree. Content that a synthesized value
80//! copies from the document is therefore reported again wherever the value is
81//! brought up to date (a heading's title holding an unresolved reference
82//! reports it where the heading is written, and again at every reference that
83//! shows that title), and each such report still points at the place where the
84//! content was written. When a lowering rule splices the synthesized value into
85//! its output ([`Lowerer::splice`](crate::core::lowering::Lowerer::splice)), the
86//! lowering adds to each report one traceback frame for each synthesized value
87//! being spliced, each pointing at the node where that copy is shown.
88//!
89//! # The identifiers of synthesized values
90//!
91//! Synthesized values are numbered per stage call: the values that one stage
92//! call brings up to date, including those of the catch-ups nested inside it,
93//! are numbered from zero. Two calls therefore assign the same identifiers to
94//! different trees. Two rules follow, stated in full at
95//! [`StageCx::resolve_value`]: never store such an identifier, or a node address
96//! inside such a tree, in a table that the runner folds into the run's store;
97//! and never write such a tree by its identifier when a table serializes itself
98//! ([`Table::project`](crate::core::data::table::Table::project)).
99//!
100//! During value catch-up, [`StageCx::walk`] still walks the document's trees,
101//! not the synthesized value.
102//!
103//! The stages run during value catch-up report nothing on the progress sheet:
104//! they receive the calling stage's scope with the depth limit 0, so they
105//! declare no row, and they still see the cancellation and still write log
106//! lines ([`StageCx::progress`]).
107
108use std::any::Any;
109use std::cell::{Cell, RefCell};
110use std::collections::BTreeMap;
111use std::fmt;
112use std::rc::Rc;
113use std::sync::Arc;
114
115use techy::core::node::{NodeRef, NodeTree};
116use techy::error::{Diagnostic, DiagnosticInfo};
117
118use crate::model::addr::{NodeAddr, TreeId};
119use crate::model::doc::{Doc, Fragment, FragmentLayout};
120use crate::model::names::{CapName, ElementName, StageName};
121use crate::model::options::{OptionError, Options, ResolvedOptions};
122use serde_json::Value;
123use crate::core::plan::Plan;
124use crate::core::plan::build::{request_subject, unchecked_output_message};
125use crate::core::registry::StageKind;
126use crate::core::registry::frozen::{FlmRegistry, StageIdx};
127use crate::core::services::Services;
128use crate::core::stage::{RewriteError, Scope};
129use crate::core::data::store::{
130 AccessError, Computed, ComputedView, FoldTarget, StageOut, StoreError, fold_outs,
131};
132use crate::core::data::table::{SingletonTable, TableKey};
133use crate::core::run::order::{DocPosition, RunOrder};
134use crate::lang::structural::StructuralElements;
135use crate::lang::{Flm, FlmDiagnostic, FlmDiagnostics, FlmSpan};
136use crate::progress;
137
138/// Diagnostic condition `flm.run.missing-entry`, reported at Error severity: a
139/// table holds no entry for a node inside a synthesized value, where a node of
140/// the document would have one.
141///
142/// A synthesized value states no fact about the document, so no stage numbered
143/// a heading inside one or counted a footnote there. The code that finds the
144/// missing entry reports this condition instead of guessing the missing data;
145/// [`StageCx::missing_entry`] builds the diagnostic.
146#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
147#[diagnostic(
148 id = "flm.run.missing-entry",
149 message = "this `{element}` element has no entry in table `{table}` (written by \
150 `{producer}`), because it is inside content generated during processing, for \
151 which no such data is recorded"
152)]
153pub struct MissingEntry {
154 /// The name of the table that was read.
155 pub table: String,
156 /// The name of the stage that the plan scheduled to write the table, or
157 /// `nobody` when no stage of the plan writes it.
158 pub producer: String,
159 /// The name of the element of the node that the data was wanted for.
160 pub element: String,
161}
162
163/// Diagnostic condition `flm.synth.nesting-too-deep`: during value catch-up, a
164/// rewrite stage found a synthesized value nested more deeply than the
165/// recursion guard allows ([the recursion guard and worker
166/// threads](crate::guide::concepts_overview#the-recursion-guard-and-worker-threads)).
167///
168/// Value catch-up then returns [`CatchUpError::NestingTooDeep`], which carries
169/// this diagnostic, and the synthesized value is left unchanged.
170#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
171#[diagnostic(
172 id = "flm.synth.nesting-too-deep",
173 message = "in content generated during processing, {detail}"
174)]
175pub struct SynthNestingTooDeep {
176 /// The message of the diagnostic that the rewrite stage reported, which
177 /// states how deep the content nests.
178 pub detail: String,
179}
180
181/// Diagnostic condition `flm.run.ignored-preference`, reported at Warning
182/// severity: the plan request (named by its workflow when it was made from one)
183/// preferred a stage that the plan could not schedule, because scheduling
184/// another stage that provides the same capability had already ruled it out.
185///
186/// The run reports it once, before any other diagnostic of the run: the plan
187/// was built, so the run goes ahead, but the caller did not get what it asked
188/// for. It is the run-time counterpart of
189/// [`PlanWarning::IgnoredPreference`](crate::core::plan::PlanWarning::IgnoredPreference).
190#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
191#[diagnostic(id = "flm.run.ignored-preference")]
192pub struct IgnoredPreference {
193 /// The name of the stage that the plan request preferred.
194 pub stage: String,
195 /// The name of the stage scheduled instead, which ruled the preferred
196 /// stage out.
197 pub excluded_by: String,
198 /// A capability that both stages provide.
199 pub over: String,
200 /// The name of the workflow the plan request was made from, or `None` for
201 /// a request built by hand
202 /// ([`PlanRequest::workflow`](crate::core::plan::PlanRequest::workflow)).
203 pub workflow: Option<String>,
204}
205
206impl fmt::Display for IgnoredPreference {
207 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208 write!(
209 f,
210 "{} prefers the stage `{}`, but that stage cannot be scheduled: the scheduled \
211 stage `{}` also provides `{}`, and only one scheduled stage may provide each \
212 capability",
213 request_subject(self.workflow.as_deref()),
214 self.stage,
215 self.excluded_by,
216 self.over
217 )
218 }
219}
220
221/// Diagnostic condition `flm.run.preferred-rule-set-aside`, reported at
222/// Warning severity: the plan request (named by its workflow when it was made
223/// from one) preferred a lowering rule that is set aside, so no plan can choose
224/// it.
225///
226/// A peer declaration is a feature's forward declaration of something that
227/// another feature owns, such as a backend, a presentation element or a table
228/// ([`PeerName`](crate::core::registry::PeerName)). A lowering rule is set
229/// aside when a peer declaration it depends on resolves to nothing: the rule is
230/// excluded from rule selection. The run reports this condition once, before
231/// any other diagnostic of the run, and goes ahead with the rule that the rule
232/// selection order ([`SelectedRules`](crate::core::plan::SelectedRules)) chose
233/// instead. It is the run-time counterpart of
234/// [`PlanWarning::PreferredRuleSetAside`](crate::core::plan::PlanWarning::PreferredRuleSetAside).
235#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
236#[diagnostic(id = "flm.run.preferred-rule-set-aside")]
237pub struct PreferredRuleSetAside {
238 /// The name of the lowering rule that the plan request preferred.
239 pub rule: String,
240 /// The name of the backend that the preference was stated for.
241 pub backend: String,
242 /// The peer declarations that did not resolve, each written as its kind
243 /// followed by its name, in the order in which the rule declares them.
244 pub unresolved: Vec<String>,
245 /// The name of the workflow the plan request was made from, or `None` for
246 /// a request built by hand
247 /// ([`PlanRequest::workflow`](crate::core::plan::PlanRequest::workflow)).
248 pub workflow: Option<String>,
249}
250
251impl fmt::Display for PreferredRuleSetAside {
252 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253 write!(
254 f,
255 "{} prefers the lowering rule `{}` on backend `{}`, but that rule cannot be used: \
256 it depends on {}, which no registered feature declares",
257 request_subject(self.workflow.as_deref()),
258 self.rule,
259 self.backend,
260 self.unresolved.join(", ")
261 )
262 }
263}
264
265/// Diagnostic condition `flm.run.preferred-rule-not-candidate`, reported at
266/// Warning severity: the plan request (named by its workflow when it was made
267/// from one) preferred, for a backend, a lowering rule that is not a candidate
268/// for any element on that backend.
269///
270/// A rule marked as the default for named backends
271/// ([`DefaultMark::OnBackends`](crate::core::lowering::DefaultMark::OnBackends))
272/// belongs to those backends and is never chosen on any other. The run reports
273/// this condition once, before any other diagnostic of the run, and goes ahead
274/// with the rule that the rule selection order
275/// ([`SelectedRules`](crate::core::plan::SelectedRules)) chose instead. It is
276/// the run-time counterpart of
277/// [`PlanWarning::PreferredRuleNotCandidate`](crate::core::plan::PlanWarning::PreferredRuleNotCandidate).
278#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
279#[diagnostic(id = "flm.run.preferred-rule-not-candidate")]
280pub struct PreferredRuleNotCandidate {
281 /// The name of the lowering rule that the plan request preferred.
282 pub rule: String,
283 /// The name of the backend that the preference was stated for.
284 pub backend: String,
285 /// The name of the workflow the plan request was made from, or `None` for
286 /// a request built by hand
287 /// ([`PlanRequest::workflow`](crate::core::plan::PlanRequest::workflow)).
288 pub workflow: Option<String>,
289}
290
291impl fmt::Display for PreferredRuleNotCandidate {
292 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293 write!(
294 f,
295 "{} prefers the lowering rule `{}` on backend `{}`, but that rule is marked as the \
296 default on other backends only, which restricts it to those backends",
297 request_subject(self.workflow.as_deref()),
298 self.rule,
299 self.backend
300 )
301 }
302}
303
304/// Diagnostic condition `flm.run.unchecked-output`, reported at Warning
305/// severity: lowering rules of one feature write output on one backend that
306/// nothing checks before the program reading it does.
307///
308/// A rule declares such output in
309/// [`LoweringDecl::unchecked_output`](crate::core::lowering::LoweringDecl::unchecked_output).
310/// The run reports this condition once per backend and feature, before any
311/// other diagnostic of the run. It is the run-time counterpart of
312/// [`PlanWarning::UncheckedOutput`](crate::core::plan::PlanWarning::UncheckedOutput).
313#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
314#[diagnostic(id = "flm.run.unchecked-output")]
315pub struct UncheckedOutput {
316 /// The name of the feature that registered the rules.
317 pub feature: String,
318 /// The name of the backend whose output holds what the rules write.
319 pub backend: String,
320 /// What the rules write, as the rule declares it.
321 pub written: String,
322 /// What reads the output, as the rule declares it.
323 pub reader: String,
324 /// The name of the workflow the plan request was made from, or `None` for
325 /// a request built by hand
326 /// ([`PlanRequest::workflow`](crate::core::plan::PlanRequest::workflow)).
327 pub workflow: Option<String>,
328}
329
330impl fmt::Display for UncheckedOutput {
331 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
332 f.write_str(&unchecked_output_message(
333 &self.feature,
334 &self.backend,
335 &self.written,
336 &self.reader,
337 ))
338 }
339}
340
341/// The reason why value catch-up could not bring a synthesized value up to
342/// date.
343///
344/// Returned by [`StageCx::resolve_value`] and
345/// [`StageCx::resolve_value_with`]. The caller of value catch-up decides what to
346/// do. [`Lowerer::splice`](crate::core::lowering::Lowerer::splice), for example,
347/// turns the store's refusal of a fact about the document into
348/// [`LowerError::DocumentFactInValue`](crate::core::lowering::LowerError::DocumentFactInValue)
349/// and any other failure into
350/// [`LowerError::CatchUp`](crate::core::lowering::LowerError::CatchUp).
351#[derive(Debug)]
352pub enum CatchUpError {
353 /// A rewrite stage found the synthesized value nested more deeply than the
354 /// recursion guard allows. The diagnostic's condition is
355 /// [`SynthNestingTooDeep`].
356 NestingTooDeep(FlmDiagnostic),
357 /// A rewrite stage failed over the synthesized value.
358 Rewrite {
359 /// The rewrite stage that failed.
360 stage: StageName,
361 /// The one diagnostic it reported.
362 diagnostic: FlmDiagnostic,
363 },
364 /// A stage run during value catch-up produced a table piece that states a
365 /// fact about the document as a whole
366 /// ([`StoreError::DocumentFactInValue`]), which a synthesized value may not
367 /// do, or an invariant of the catch-up store failed
368 /// ([`StoreError::SecondWriter`]).
369 Store(StoreError),
370}
371
372impl CatchUpError {
373 /// Returns the one diagnostic that describes the failure, when the failure
374 /// has one.
375 ///
376 /// [`CatchUpError::Store`] has none; its `Display` text describes the
377 /// failure.
378 pub fn diagnostic(&self) -> Option<&FlmDiagnostic> {
379 match self {
380 CatchUpError::NestingTooDeep(d) => Some(d),
381 CatchUpError::Rewrite { diagnostic, .. } => Some(diagnostic),
382 CatchUpError::Store(_) => None,
383 }
384 }
385}
386
387impl fmt::Display for CatchUpError {
388 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389 match self {
390 CatchUpError::NestingTooDeep(d) => write!(f, "{}", d.message()),
391 CatchUpError::Rewrite { stage, diagnostic } => {
392 write!(
393 f,
394 "rewrite stage `{stage}` failed on content generated during processing: {}",
395 diagnostic.message()
396 )
397 }
398 CatchUpError::Store(error) => fmt::Display::fmt(error, f),
399 }
400 }
401}
402
403impl std::error::Error for CatchUpError {}
404
405impl From<StoreError> for CatchUpError {
406 fn from(error: StoreError) -> CatchUpError {
407 CatchUpError::Store(error)
408 }
409}
410
411/// What one run shares with every stage context it creates.
412pub(crate) struct RunView<'r> {
413 /// The document being processed.
414 pub doc: &'r Doc,
415 /// The registry that the plan was built from.
416 pub registry: &'r FlmRegistry,
417 /// The plan being run.
418 pub plan: &'r Plan,
419 /// The frozen tree of each of the document's trees that has one.
420 pub frozen: &'r BTreeMap<TreeId, Arc<NodeTree<Flm>>>,
421 /// The run's document order: the trees, their nodes, the placements.
422 pub order: &'r RunOrder,
423 /// From a frozen tree's address in memory to its identifier, so that a node
424 /// handed to a stage can be placed.
425 pub tree_index: &'r BTreeMap<usize, TreeId>,
426 /// The store as it was when the current batch began; every stage of a
427 /// batch reads the same version.
428 pub computed: &'r Computed,
429 /// The resolved option values of every scheduled stage.
430 pub options: &'r BTreeMap<StageIdx, Arc<ResolvedOptions>>,
431}
432
433/// The synthesized values that one stage call brought up to date, each with
434/// its address in memory and the identifier it was given.
435type ValueTrees = Vec<(usize, TreeId, Arc<NodeTree<Flm>>)>;
436
437/// The numbering of the synthesized values of one stage call, and the trees
438/// themselves, so that the address of a node inside one can be found.
439struct ValueSpace {
440 next: Cell<u32>,
441 trees: RefCell<ValueTrees>,
442}
443
444/// A synthesized value brought up to date by value catch-up: the tree after the
445/// rewrite stages, what the stages run over it computed, and the diagnostics
446/// they reported.
447///
448/// Returned by [`StageCx::resolve_value`]. Read the computed data through
449/// [`CaughtUp::view`], and report [`CaughtUp::diags`] yourself, for example by
450/// appending them to [`StageOut::diags`](crate::core::data::store::StageOut::diags):
451/// value catch-up writes nothing into the run.
452pub struct CaughtUp {
453 /// The identifier given to the synthesized value.
454 ///
455 /// It means something only inside the stage call that requested the value
456 /// catch-up, because synthesized values are numbered per stage call. Never
457 /// store it, or a node address inside this tree, in a table that the runner
458 /// folds into the run's store, and never write this tree by its identifier
459 /// when a table serializes itself. The rules are stated in full at
460 /// [`StageCx::resolve_value`].
461 pub id: TreeId,
462 /// The synthesized value as the rewrite stages left it.
463 pub tree: Arc<NodeTree<Flm>>,
464 /// The catch-up store: what the stages run over the tree computed, in a
465 /// store of its own.
466 pub scratch: Computed,
467 /// The diagnostics reported while the tree was brought up to date.
468 pub diags: FlmDiagnostics,
469}
470
471impl CaughtUp {
472 /// Returns a view of the tables that the stage of `cx` declared as reads,
473 /// reading this catch-up store before the run's store for every read,
474 /// whichever node the data is wanted for.
475 ///
476 /// A table present in the catch-up store is read whole from it; see
477 /// [`ComputedView::with_overlay`]. The lowering stage of a backend
478 /// ([`crate::stdlib::backends::lowering`]) does not read through this
479 /// view: it keeps each synthesized value's catch-up store by
480 /// the value's identifier and reads it only for an address inside that
481 /// value, so that content of another tree, lowered while the value is
482 /// lowered, reads its own tree's tables.
483 pub fn view<'a>(&'a self, cx: &StageCx<'a>) -> ComputedView<'a> {
484 cx.view.with_overlay(&self.scratch)
485 }
486}
487
488impl fmt::Debug for CaughtUp {
489 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
490 f.debug_struct("CaughtUp").field("id", &self.id).field("scratch", &self.scratch).finish()
491 }
492}
493
494/// The stage context: everything a stage may read during one call.
495///
496/// A stage context gives a stage the frozen trees, the run's document order,
497/// the tables it declared as reads, the values of the option types it
498/// declared, the registry's services, node addresses and value catch-up; the
499/// [module documentation](self) describes each.
500///
501/// The runner creates one stage context for each call: once for each tree of
502/// the run for a [`Scope::PerTree`] stage, once for a [`Scope::Document`]
503/// stage. It passes the context to [`Stage::run`](crate::core::stage::Stage::run)
504/// together with a [`StageOut`], into which the stage writes what it produces.
505/// During value catch-up, a per-tree stage receives a context for the
506/// synthesized value.
507pub struct StageCx<'a> {
508 run: &'a RunView<'a>,
509 stage: StageIdx,
510 /// For a per-tree call, which tree it is for: a document tree, or a
511 /// synthesized one being brought up to date. `None` for a document-scope
512 /// call.
513 tree: Option<TreeId>,
514 /// The tree itself, when this call is over a synthesized one. A document
515 /// tree is reached through `run.frozen` instead.
516 value_tree: Option<Arc<NodeTree<Flm>>>,
517 view: ComputedView<'a>,
518 values: Rc<ValueSpace>,
519 /// The scope of the stage's row on the progress sheet; past the depth
520 /// limit 0 during value catch-up.
521 progress: progress::Scope,
522}
523
524impl<'a> StageCx<'a> {
525 pub(crate) fn new(
526 run: &'a RunView<'a>,
527 stage: StageIdx,
528 tree: Option<TreeId>,
529 view: ComputedView<'a>,
530 progress: progress::Scope,
531 ) -> StageCx<'a> {
532 StageCx {
533 run,
534 stage,
535 tree,
536 value_tree: None,
537 view,
538 values: Rc::new(ValueSpace { next: Cell::new(0), trees: RefCell::new(Vec::new()) }),
539 progress,
540 }
541 }
542
543 /// The document being processed.
544 pub fn doc(&self) -> &'a Doc {
545 self.run.doc
546 }
547
548 /// The registry that the plan was built from.
549 pub fn registry(&self) -> &'a FlmRegistry {
550 self.run.registry
551 }
552
553 /// The plan being run.
554 pub fn plan(&self) -> &'a Plan {
555 self.run.plan
556 }
557
558 /// The name of the stage that this call is for.
559 pub fn stage_name(&self) -> &'a StageName {
560 &self.run.registry.stage(self.stage).name
561 }
562
563 /// The stage's scope: once per tree, or once for the whole document.
564 pub fn scope(&self) -> Scope {
565 self.run.registry.stage(self.stage).decl.scope
566 }
567
568 /// The scope of the stage's row on the progress sheet of the build.
569 ///
570 /// The runner owns the row, one for each scheduled stage, and the per-tree
571 /// calls of one stage share it. A stage reports its own slow work in rows
572 /// it declares under this scope ([`Scope::child`](progress::Scope::child)):
573 /// a document-scope stage one row for its items; a per-tree call one row
574 /// for the items of its tree, labeled with the tree's source, which then
575 /// stands for that tree in the count of the stage's row. Where the work
576 /// has units (a tree, an image, a formula), the stage asks
577 /// [`cancelled`](progress::Scope::cancelled) once per unit and returns as
578 /// soon as it can when the build was cancelled: what a cancelled step
579 /// produced is discarded whole, so what it returns need not be
580 /// meaningful.
581 ///
582 /// A run that reports nowhere gives [`Scope::none`](progress::Scope::none),
583 /// whose methods do nothing; the stage calls them all the same. During
584 /// value catch-up the scope is past the depth limit 0: it declares no row,
585 /// and still answers `cancelled` and still writes log lines.
586 pub fn progress(&self) -> &progress::Scope {
587 &self.progress
588 }
589
590 /// The identifier of the tree that this call is for (a tree of the run, or
591 /// a synthesized value during value catch-up), or `None` when the stage runs once for
592 /// the whole document.
593 pub fn tree_id(&self) -> Option<TreeId> {
594 self.tree
595 }
596
597 /// Returns the tree with this identifier: the frozen tree of a tree of the
598 /// run, or a synthesized value that this stage call has brought up to
599 /// date.
600 ///
601 /// `None` when the identifier is unknown, when the document tree's rewrite
602 /// failed so that it has no frozen tree, or when the tree is not a tree of
603 /// the run ([`Run::tree_order`](crate::core::run::Run::tree_order)).
604 pub fn tree(&self, id: TreeId) -> Option<Arc<NodeTree<Flm>>> {
605 if id.is_value() {
606 if self.tree == Some(id) {
607 return self.value_tree.clone();
608 }
609 return self
610 .values
611 .trees
612 .borrow()
613 .iter()
614 .find(|(_, tree_id, _)| *tree_id == id)
615 .map(|(_, _, tree)| Arc::clone(tree));
616 }
617 self.run.frozen.get(&id).cloned()
618 }
619
620 /// Returns the frozen tree of a tree of the run, borrowed rather than
621 /// shared.
622 ///
623 /// Unlike [`StageCx::tree`], this never returns a synthesized value.
624 pub fn frozen_tree(&self, id: TreeId) -> Option<&'a Arc<NodeTree<Flm>>> {
625 self.run.frozen.get(&id)
626 }
627
628 /// Returns the tree that this call is for, if the call is for one: a
629 /// frozen tree, or a synthesized value during value catch-up.
630 pub fn my_tree(&self) -> Option<Arc<NodeTree<Flm>>> {
631 self.tree.and_then(|id| self.tree(id))
632 }
633
634 /// Returns the fragment that a document tree was parsed from
635 /// ([`Fragment`]: one piece of source as the parser delivered it).
636 pub fn fragment(&self, id: TreeId) -> Option<&'a Arc<Fragment>> {
637 self.run.doc.content().fragment(id)
638 }
639
640 /// Returns how a document tree's content is laid out: as inline content, as
641 /// blocks, or as inline content followed by blocks ([`FragmentLayout`]).
642 pub fn layout(&self, id: TreeId) -> Option<FragmentLayout> {
643 self.fragment(id).map(|fragment| fragment.layout())
644 }
645
646 /// Returns the run's trees, each with its identifier and its frozen tree,
647 /// in the run's order of the trees: the trees that the walk
648 /// ([`StageCx::walk`]) reaches, in the order in which it enters them. A
649 /// tree that the walk does not reach is not a tree of the run
650 /// ([`Run::tree_order`]).
651 ///
652 /// A placed tree is entered at the node that places it, in the middle of
653 /// the tree that places it, so reading the trees one after the other is not
654 /// reading the document in order. A document-scope stage that needs
655 /// document order across trees uses [`StageCx::walk`], or sorts what it
656 /// gathers from several trees by [`StageCx::position`].
657 ///
658 /// [`Run::tree_order`]: crate::core::run::Run::tree_order
659 pub fn trees(&self) -> impl Iterator<Item = (TreeId, &'a Arc<NodeTree<Flm>>)> + 'a {
660 let run = self.run;
661 run.order.trees().iter().filter_map(move |id| run.frozen.get(id).map(|tree| (*id, tree)))
662 }
663
664 /// Returns every node of every tree of the run, with its address, in
665 /// document order.
666 ///
667 /// This is the document's walk ([`DocContent::walk`]) applied to the frozen
668 /// trees: the listed trees in order, each tree once, within a tree the root
669 /// and then its descendants in the order in which they are written, and a
670 /// placed tree entered at the node that places it, its nodes following that
671 /// node immediately and coming before the node's own children. A tree that
672 /// the walk does not reach (its placing node removed by a rewrite stage, or
673 /// the tree that includes it failed its rewrite) is not a tree of the run
674 /// ([`Run::tree_order`]). A document-scope stage reads the whole document
675 /// this way. During value catch-up, the walk still covers the document's
676 /// trees, not the synthesized value.
677 ///
678 /// [`DocContent::walk`]: crate::model::doc::DocContent::walk
679 /// [`Run::tree_order`]: crate::core::run::Run::tree_order
680 pub fn walk(&self) -> FrozenWalk<'a> {
681 FrozenWalk::new(self.run)
682 }
683
684 /// Returns the position of the node at `addr` in the run's document order,
685 /// the order of [`StageCx::walk`]: of two nodes, the one with the smaller
686 /// position comes first in the document.
687 ///
688 /// A document-scope stage that gathers nodes, or records keyed by nodes,
689 /// from several trees sorts them by position. `None` for a node of none of
690 /// the run's trees, for example a node of a synthesized value.
691 pub fn position(&self, addr: NodeAddr) -> Option<DocPosition> {
692 self.run.order.position(addr)
693 }
694
695 /// Returns the tree of the document that the node at `addr`, a node of a
696 /// frozen tree, places, or `None` when it places none.
697 ///
698 /// The document records its placements by the placing node as parsed
699 /// ([`DocContent::placement_of`]); the run finds each placing node again
700 /// in the frozen trees, where a stage reaches it. When a rewrite stage
701 /// copied a placing node, only its first copy in document order places the
702 /// tree ([`PlacedTwice`](crate::core::run::PlacedTwice)).
703 ///
704 /// [`DocContent::placement_of`]: crate::model::doc::DocContent::placement_of
705 pub fn placement_of(&self, addr: NodeAddr) -> Option<TreeId> {
706 self.run.order.placement_of(addr)
707 }
708
709 /// Returns the view of the store that this call reads through, which
710 /// refuses a read the stage did not declare. During value catch-up, the
711 /// view reads the catch-up store before the run's store.
712 pub fn view(&self) -> &ComputedView<'a> {
713 &self.view
714 }
715
716 /// Reads a table that the stage declared as a read
717 /// ([`Needs::reads`](crate::core::stage::Needs::reads)), through a typed
718 /// table key.
719 ///
720 /// `Ok(None)` means that no stage of the plan provides the table, which
721 /// can only happen for a table declared as an optional read
722 /// ([`Needs::reads_opt`](crate::core::stage::Needs::reads_opt)).
723 ///
724 /// # Errors
725 ///
726 /// Returns [`AccessError`] when the stage did not declare this read, or
727 /// declared it under another value type.
728 pub fn get<K: TableKey>(&self, key: K) -> Result<Option<&'a K::Table>, AccessError> {
729 self.view.get(key)
730 }
731
732 /// Reads the one table of a value type `T` that exactly one table uses
733 /// ([`SingletonTable`]).
734 ///
735 /// The same as [`StageCx::get`] with the table name `T::NAME`.
736 ///
737 /// # Errors
738 ///
739 /// Returns [`AccessError`] when the stage did not declare this read, or
740 /// declared it under another value type.
741 pub fn get_singleton<T: SingletonTable>(&self) -> Result<Option<&'a T>, AccessError> {
742 self.view.get_singleton::<T>()
743 }
744
745 /// Returns the value of an option type that the stage declared as a read:
746 /// the value set on the plan request, else the value set on the document,
747 /// else the type's default ([option types and
748 /// values](crate::model::options)). The value is resolved once for the
749 /// whole run.
750 ///
751 /// # Errors
752 ///
753 /// Returns [`OptionError`] when the stage did not declare that option
754 /// type.
755 pub fn option<T: Options>(&self) -> Result<&'a T, OptionError> {
756 self.run.options[&self.stage].get::<T>()
757 }
758
759 /// Returns the value of the option type declared from data under the name
760 /// `name`, which the stage declared as a read
761 /// ([`Needs::option_named`](crate::core::stage::Needs::option_named)): the
762 /// data as written on the plan request, else on the document, else the
763 /// empty map. Otherwise as [`StageCx::option`].
764 ///
765 /// # Errors
766 ///
767 /// Returns [`OptionError::UndeclaredRead`], with the name, when the stage
768 /// did not declare that read.
769 pub fn option_named(&self, name: &str) -> Result<&'a Value, OptionError> {
770 self.run.options[&self.stage].get_named(name)
771 }
772
773 /// Returns every option type that the stage declared, each with its
774 /// resolved value.
775 ///
776 /// [`StageCx::option`] reads one value. A stage that reads option values
777 /// on behalf of other code (a lowering stage, for its lowering rules)
778 /// passes this whole set on.
779 pub fn options(&self) -> &'a ResolvedOptions {
780 &self.run.options[&self.stage]
781 }
782
783 /// Returns every service that the registry holds ([`Services`]; see
784 /// [services](crate::core::services) for what a service is).
785 pub fn services_all(&self) -> &'a Services {
786 self.run.registry.services()
787 }
788
789 /// Returns one service of type `S`: of the service slots whose values have
790 /// type `S`, taken in name order, the first that holds a contribution gives
791 /// the one that takes precedence in it (between features, the contribution
792 /// of the feature placed last in the feature order); `None` when no such
793 /// slot holds a contribution. See [`Services::service`].
794 pub fn service<S: ?Sized + Any + Send + Sync>(&self) -> Option<&'a S> {
795 self.run.registry.services().service::<S>()
796 }
797
798 /// Returns every service of type `S`: the contributions of every service
799 /// slot whose values have type `S`, the slots in name order. See
800 /// [`Services::services`].
801 pub fn services<S: ?Sized + Any + Send + Sync>(&self) -> impl Iterator<Item = &'a S> + 'a {
802 self.run.registry.services().services::<S>()
803 }
804
805 /// Returns the address of `node`, by which computed data about the node is
806 /// keyed.
807 ///
808 /// `None` when the node belongs to neither a frozen tree of the document
809 /// nor a synthesized tree this stage call has brought up to date.
810 pub fn addr(&self, node: &NodeRef<'_, Flm>) -> Option<NodeAddr> {
811 let key = node.tree() as *const NodeTree<Flm> as usize;
812 if let Some(id) = self.run.tree_index.get(&key) {
813 return Some(NodeAddr::new(*id, node.id()));
814 }
815 if let (Some(id), Some(tree)) = (self.tree, &self.value_tree) {
816 if Arc::as_ptr(tree) as usize == key {
817 return Some(NodeAddr::new(id, node.id()));
818 }
819 }
820 self.values
821 .trees
822 .borrow()
823 .iter()
824 .find(|(ptr, _, _)| *ptr == key)
825 .map(|(_, id, _)| NodeAddr::new(*id, node.id()))
826 }
827
828 /// Builds the Error diagnostic [`MissingEntry`], for a node inside a
829 /// synthesized value for which the table `table` holds no entry.
830 ///
831 /// The diagnostic identifies the table, the stage that the plan scheduled
832 /// to write it (or `nobody`), and `element`, the element of the node; it is
833 /// reported at `span`. This method only builds the diagnostic: the caller
834 /// reports it, for example by appending it to
835 /// [`StageOut::diags`](crate::core::data::store::StageOut::diags).
836 pub fn missing_entry(
837 &self,
838 table: &CapName,
839 element: &ElementName,
840 span: FlmSpan,
841 ) -> FlmDiagnostic {
842 let producer = self
843 .view
844 .producer_of(table)
845 .map(|s| s.to_string())
846 .unwrap_or_else(|| "nobody".to_string());
847 Diagnostic::error(
848 MissingEntry { table: table.to_string(), producer, element: element.to_string() },
849 span,
850 )
851 }
852
853 /// Brings a synthesized value up to date through value catch-up, so that it
854 /// can be rendered like a tree of the document.
855 ///
856 /// A synthesized value is a small tree that a stage builds while a run is
857 /// under way ([synthesized
858 /// values](crate::guide::concepts_overview#synthesized-values)). The
859 /// plan's rewrite stages run over `value`, then the per-tree stages that
860 /// this stage depends on
861 /// ([`Plan::per_tree_closure`](crate::core::plan::Plan::per_tree_closure))
862 /// run over it alone; what they compute and report is returned in
863 /// [`CaughtUp`]. The run's store is not written. See [value
864 /// catch-up](crate::guide::concepts_overview#value-catch-up).
865 ///
866 /// The value's content is laid out with the default [`FragmentLayout`]:
867 /// inline content, followed by blocks if a block appears.
868 /// [`StageCx::resolve_value_with`] sets the layout explicitly.
869 ///
870 /// # Tables read during value catch-up
871 ///
872 /// A table that the stages run during value catch-up write is read from
873 /// the catch-up store, whole: a stage run over the value reads the value's
874 /// contribution to that table and nothing of the document's. A stage that
875 /// needs data about the whole document must therefore read a table that no
876 /// per-tree stage run during the catch-up writes; see
877 /// [`ComputedView::with_overlay`].
878 ///
879 /// # The identifiers of the synthesized value
880 ///
881 /// Synthesized values are numbered per stage call, so this value's
882 /// identifier, and every node address inside it, means something only
883 /// inside this call; another call assigns the same identifiers to a
884 /// different tree. Two rules follow:
885 ///
886 /// - **Never put such an address into a table piece that the runner folds
887 /// into the run's store.** Entries belonging to two different trees would
888 /// collide there without anything noticing.
889 /// - **Never write such a tree by its identifier when a table serializes
890 /// itself** ([`Table::project`](crate::core::data::table::Table::project)).
891 /// A reader of the serialized table cannot resolve the identifier; a
892 /// table writes a stored synthesized value in full instead
893 /// ([`ProjectCx::tree`](crate::core::data::table::ProjectCx::tree)).
894 ///
895 /// # Errors
896 ///
897 /// Returns [`CatchUpError`] when a rewrite stage refused or failed over the
898 /// value, or when a stage run over the value produced a table piece that
899 /// states a fact about the document as a whole.
900 ///
901 /// # Panics
902 ///
903 /// A rewrite stage or another stage that panics while it runs over the
904 /// value propagates the panic out of this call, as out of
905 /// [`Run::step`](crate::core::run::Run::step). A panic means a defect in
906 /// that stage; a problem with the document is reported as a diagnostic.
907 pub fn resolve_value(&self, value: &Arc<NodeTree<Flm>>) -> Result<CaughtUp, CatchUpError> {
908 self.resolve_value_with(value, FragmentLayout::default())
909 }
910
911 /// Brings a synthesized value up to date through value catch-up, laying out
912 /// its content with `layout`.
913 ///
914 /// The same as [`StageCx::resolve_value`] in every other respect, including
915 /// the rules about what the stages read and about the value's identifiers,
916 /// except that `layout` says whether the value's content is inline content,
917 /// blocks, or inline content followed by blocks.
918 ///
919 /// # Errors
920 ///
921 /// Returns [`CatchUpError`], as [`StageCx::resolve_value`] does.
922 ///
923 /// # Panics
924 ///
925 /// As [`StageCx::resolve_value`]: a rewrite stage or another stage that
926 /// panics while it runs over the value propagates the panic out of this
927 /// call.
928 pub fn resolve_value_with(
929 &self,
930 value: &Arc<NodeTree<Flm>>,
931 layout: FragmentLayout,
932 ) -> Result<CaughtUp, CatchUpError> {
933 let run = self.run;
934 let index = self.values.next.get();
935 self.values.next.set(index + 1);
936 let id = TreeId::value(index);
937 let mut diags = FlmDiagnostics::new();
938 let mut current = Arc::clone(value);
939 for rewrite in run.plan.rewrites() {
940 let entry = run.registry.stage(*rewrite);
941 let StageKind::Rewrite(stage) = &entry.kind else { continue };
942 let cx = RewriteCx::new(run.registry, id, layout, &run.options[rewrite]);
943 match stage.rewrite(id, ¤t, &cx, &mut diags) {
944 Ok(next) => current = next,
945 Err(RewriteError::NestingTooDeep(diagnostic)) => {
946 let detail = diagnostic.message();
947 return Err(CatchUpError::NestingTooDeep(Diagnostic::error(
948 SynthNestingTooDeep { detail },
949 diagnostic.span().clone(),
950 )));
951 }
952 Err(error) => {
953 return Err(CatchUpError::Rewrite {
954 stage: entry.name.clone(),
955 diagnostic: error.diagnostic().clone(),
956 });
957 }
958 }
959 }
960 self.values.trees.borrow_mut().push((
961 Arc::as_ptr(¤t) as usize,
962 id,
963 Arc::clone(¤t),
964 ));
965 let mut scratch = Computed::new();
966 // The stages run over the value add no row to the sheet.
967 let progress = self.progress.with_depth_limit(0);
968 for idx in run.plan.per_tree_closure(self.stage) {
969 let entry = run.registry.stage(idx);
970 let StageKind::Pipeline(stage) = &entry.kind else { continue };
971 let plan = run.plan.manifest(idx).expect("a scheduled stage has a manifest");
972 let mut out = StageOut::new(&entry.name, &plan.writes);
973 {
974 let view = ComputedView::new(&entry.name, &plan.reads, run.computed)
975 .with_overlay(&scratch);
976 let cx = StageCx {
977 run,
978 stage: idx,
979 tree: Some(id),
980 value_tree: Some(Arc::clone(¤t)),
981 view,
982 values: Rc::clone(&self.values),
983 progress: progress.clone(),
984 };
985 stage.run(&cx, &mut out);
986 }
987 fold_outs(
988 &entry.name,
989 &plan.writes,
990 vec![out],
991 FoldTarget::Scratch,
992 &mut scratch,
993 &mut diags,
994 )?;
995 }
996 Ok(CaughtUp { id, tree: current, scratch, diags })
997 }
998}
999
1000impl fmt::Debug for StageCx<'_> {
1001 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1002 f.debug_struct("StageCx")
1003 .field("stage", self.stage_name())
1004 .field("tree", &self.tree)
1005 .finish()
1006 }
1007}
1008
1009/// An iterator over every node of every tree of the run, in document order,
1010/// with its address.
1011///
1012/// Created by [`StageCx::walk`], which describes the order: the document's walk
1013/// applied to the frozen trees, a placed tree entered at the node that places
1014/// it, over the run's trees only.
1015pub struct FrozenWalk<'a> {
1016 run: &'a RunView<'a>,
1017 position: usize,
1018}
1019
1020impl<'a> FrozenWalk<'a> {
1021 fn new(run: &'a RunView<'a>) -> FrozenWalk<'a> {
1022 FrozenWalk { run, position: 0 }
1023 }
1024}
1025
1026impl<'a> Iterator for FrozenWalk<'a> {
1027 type Item = (NodeAddr, NodeRef<'a, Flm>);
1028
1029 fn next(&mut self) -> Option<(NodeAddr, NodeRef<'a, Flm>)> {
1030 let run = self.run;
1031 loop {
1032 let addr = *run.order.walk().get(self.position)?;
1033 self.position += 1;
1034 if let Some(node) = run.frozen.get(&addr.tree).and_then(|tree| tree.get(addr.node)) {
1035 return Some((addr, node));
1036 }
1037 }
1038 }
1039
1040 fn size_hint(&self) -> (usize, Option<usize>) {
1041 (0, Some(self.run.order.walk().len().saturating_sub(self.position)))
1042 }
1043}
1044
1045/// Everything a rewrite stage may read during one call: which tree it is
1046/// rewriting, how that tree's content is laid out, the registry, and the
1047/// option types the rewrite stage declared.
1048///
1049/// A rewrite stage runs before the document's trees are frozen, turns one tree
1050/// into another, reads no computed data, and publishes the trees it produced in
1051/// a table named after the capability it provides
1052/// ([`RewriteStage`](crate::core::stage::RewriteStage)). The runner creates one
1053/// `RewriteCx` for each call and passes it to
1054/// [`RewriteStage::rewrite`](crate::core::stage::RewriteStage::rewrite). A
1055/// `RewriteCx` gives no access to any table: rewrite stages run before anything
1056/// is computed, and the type enforces that they read no computed data.
1057pub struct RewriteCx<'a> {
1058 registry: &'a FlmRegistry,
1059 tree: TreeId,
1060 layout: FragmentLayout,
1061 options: &'a ResolvedOptions,
1062}
1063
1064impl<'a> RewriteCx<'a> {
1065 pub(crate) fn new(
1066 registry: &'a FlmRegistry,
1067 tree: TreeId,
1068 layout: FragmentLayout,
1069 options: &'a ResolvedOptions,
1070 ) -> RewriteCx<'a> {
1071 RewriteCx { registry, tree, layout, options }
1072 }
1073
1074 /// The registry that the plan was built from.
1075 pub fn registry(&self) -> &'a FlmRegistry {
1076 self.registry
1077 }
1078
1079 /// Returns the structural elements of this registry: the elements of the
1080 /// node shapes that no feature declares, such as text, groups and
1081 /// paragraph breaks ([`StructuralElements`]).
1082 pub fn structural(&self) -> &'a Arc<StructuralElements> {
1083 self.registry.structural()
1084 }
1085
1086 /// The identifier of the tree being rewritten: a document tree, or a
1087 /// synthesized value being brought up to date by value catch-up.
1088 pub fn tree_id(&self) -> TreeId {
1089 self.tree
1090 }
1091
1092 /// How the tree's content is laid out: as inline content, as blocks, or as
1093 /// inline content followed by blocks ([`FragmentLayout`]).
1094 pub fn layout(&self) -> FragmentLayout {
1095 self.layout
1096 }
1097
1098 /// Returns the value of an option type that the rewrite stage declared as
1099 /// a read: the value set on the plan request, else the value set on the
1100 /// document, else the type's default.
1101 ///
1102 /// # Errors
1103 ///
1104 /// Returns [`OptionError`] when the rewrite stage did not declare that
1105 /// option type.
1106 pub fn option<T: Options>(&self) -> Result<&'a T, OptionError> {
1107 self.options.get::<T>()
1108 }
1109
1110 /// Returns the value of the option type declared from data under the name
1111 /// `name`, which the rewrite stage declared as a read: the data as written
1112 /// on the plan request, else on the document, else the empty map.
1113 ///
1114 /// # Errors
1115 ///
1116 /// Returns [`OptionError::UndeclaredRead`], with the name, when the rewrite
1117 /// stage did not declare that read.
1118 pub fn option_named(&self, name: &str) -> Result<&'a Value, OptionError> {
1119 self.options.get_named(name)
1120 }
1121}
1122
1123impl fmt::Debug for RewriteCx<'_> {
1124 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1125 f.debug_struct("RewriteCx").field("tree", &self.tree).field("layout", &self.layout).finish()
1126 }
1127}