flm_core/core/run/runner.rs
1//! The [`Run`], one execution of one plan over one document: how it is
2//! constructed, how it executes, and the diagnostics it reports.
3//!
4//! A run is one execution of one plan over one document; it owns the frozen
5//! trees, the store and the diagnostics ([`Run`]). Constructing a run checks its
6//! inputs; executing it runs the plan's stages batch by batch. See also
7//! [running a plan](crate::guide::pipeline#running-a-plan) and, for an
8//! embedding program, [running](crate::guide::embedding#running).
9//!
10//! # Constructing a run
11//!
12//! [`Run::new`] takes the document, the plan and the [`Externals`] that the
13//! caller installs. It first checks the option values set on the document
14//! against the registry's declarations. It then checks each installed value:
15//! the registry must declare the table, the table must be declared as external
16//! ([`FeatureBuilder::external_table`](crate::core::registry::FeatureBuilder::external_table)),
17//! the value must be of the table's declared type, and a value that
18//! carries a [`Stamp`] must have been produced under the same registry, rewrite
19//! stages and option values as this run. Finally, every external table that the
20//! plan needs must have a value. Each failure is a [`RunError`]. `Run::new` also
21//! resolves the option values of every scheduled stage once, for the whole
22//! run. Nothing is executed.
23//!
24//! # Executing a run
25//!
26//! Execution runs the rewrite stages first, then the plan's batches in order. A
27//! batch is a group of stages of which none depends on another stage of the
28//! same batch, so they may run at the same time
29//! ([`Plan::batches`](crate::core::plan::Plan::batches)).
30//!
31//! 1. **The rewrite stages.** Each tree of the document goes through every
32//! rewrite stage of the plan, in the plan's order, each one's output feeding
33//! the next; the trees are rewritten independently of each other. Each
34//! rewrite stage's output for every tree is published as that rewrite
35//! stage's own table, and the last output is the tree's frozen tree. A
36//! rewrite stage that fails on a tree records its one Error diagnostic, and
37//! that tree has no frozen tree: no later stage reads it, the tables of the
38//! rewrite stages that ran before keep their version of it, and the
39//! document's other trees are unaffected.
40//!
41//! When the rewrite stages are over, the run computes its document order
42//! ([`crate::core::run::order`]): the document's walk applied to the frozen
43//! trees, a placed tree entered at the node that places it. Every later
44//! stage reads this order. The run's trees are the trees that this walk
45//! reaches: a tree whose placing node a rewrite stage removed, or whose
46//! including tree failed its rewrite, is read by no later stage and appears
47//! in no output, its content dropped with the node that placed it.
48//! 2. **Each batch of stages.** A per-tree stage (a stage of
49//! [`Scope::PerTree`]) runs once for each tree of the run; a document-scope
50//! stage (a stage of [`Scope::Document`]) runs once for the whole document. Every stage of a batch reads the
51//! store as it was when the batch began, so the stages of one batch, and the
52//! calls of one per-tree stage, may run at the same time. When the batch is
53//! over, the runner folds the table pieces into the store: each stage's
54//! table pieces in the run's order of the trees (the order in which the walk
55//! enters them), the stages in the plan's order, and each stage's tables in
56//! the registry's table order. Nothing of this depends on the order in which
57//! the work finished, so a parallel and a sequential run produce the same
58//! bytes.
59//! 3. **The error gate.** Before the first batch that holds a stage with
60//! effects outside the store, the error gate stops a run that has recorded
61//! an Error diagnostic, from parsing or from the stages, unless
62//! [`RunOptions::continue_with_errors`] is set. A document with errors
63//! therefore produces no effects outside the store unless the caller asks
64//! for them; see [`RunOptions`] and [the error
65//! gate](crate::guide::embedding#the-error-gate).
66//!
67//! [`Run::execute`] runs to the end; [`Run::step`] runs one step, the rewrite
68//! stages first and then one batch per call. Stepping changes when the work
69//! happens, never what is computed: the batches are fixed and the folds do not
70//! depend on timing.
71//!
72//! # Progress and cancellation
73//!
74//! A run given a [`Scope`](crate::progress::Scope) of a progress sheet
75//! ([`Run::with_progress`]) declares its rows under it: one row of kind
76//! `flm.run.rewrites`, which counts the trees the rewrite stages run over, and
77//! one row for each scheduled stage, in the plan's order, whose kind is the
78//! stage's name. A stage's row starts when the stage's first call begins and
79//! ends when its last call returns; the row of a per-tree stage counts the
80//! trees of the run. A stage receives the scope of its row
81//! ([`StageCx::progress`]) and declares the rows of its own slow work under
82//! it; a rewrite stage receives none. The row of a stage that the error gate
83//! keeps from running ends as not run; the row of a stage that panics, and
84//! every row running when the build is cancelled, ends as failed.
85//!
86//! The run asks whether the build was cancelled at the start of each step,
87//! before each call of a stage (each per-tree call, each tree of the rewrite
88//! stages), and once when the calls of a step have returned. A cancelled step
89//! produces nothing: the calls not yet begun are skipped, everything the step
90//! computed or reported is discarded, as when a stage panics, and the run is
91//! over with the outcome [`RunOutcome::Cancelled`]. The tables and the
92//! diagnostics of the steps completed before stay readable. A run that
93//! completes a step therefore produces what it would have produced without a
94//! sheet. Reporting never changes what is computed.
95//!
96//! # Worker threads
97//!
98//! The rewrite stages and every batch run on a worker thread. A worker thread is
99//! a thread that declares its stack size with
100//! [`mark_worker_thread`](crate::lang::guard::mark_worker_thread); every guarded
101//! run (a parse, a rewrite, an emit) must execute on one
102//! ([`on_worker_thread`](crate::lang::guard::on_worker_thread)), and its budget
103//! is the stack that remains on the thread, less the reserved share that the
104//! thread declares and the library's own margin. Under the Cargo
105//! feature `parallel` of `flm-core`, unless [`RunOptions::sequential`] is set,
106//! the work runs on the threads of the runner's own pool, which are created
107//! with [`WORKER_STACK_SIZE`](crate::lang::guard::WORKER_STACK_SIZE) bytes of
108//! stack and marked with this size and the default reserved share
109//! ([`WorkerStack::new`](crate::lang::guard::WorkerStack::new)).
110//! Otherwise it runs on the calling thread when that thread is marked as a
111//! worker thread, and on a thread created for the purpose when it is not.
112//!
113//! # Diagnostics
114//!
115//! [`Run::diagnostics`] returns a [`DiagnosticsView`]: each fragment's parse
116//! diagnostics first, in the order in which the document's walk reaches the
117//! fragments and once per fragment however many times that fragment is placed,
118//! then the diagnostics that the run produced. [`Run::pipeline_diagnostics`]
119//! returns the second part alone. The run produces its diagnostics in this
120//! order: the warnings about the preferences of the plan request that the plan
121//! could not follow ([`Plan::warnings`](crate::core::plan::Plan::warnings)), the diagnostics of
122//! the rewrite stages tree by tree, the [`PlacedTwice`] diagnostics, and then
123//! the diagnostics of the stages, batch by batch.
124//!
125//! [`PlacedTwice`]: crate::core::run::PlacedTwice
126
127use std::collections::{BTreeMap, BTreeSet};
128use std::fmt;
129use std::sync::Arc;
130
131use techy::core::node::{NodeRef, NodeTree};
132use techy::error::{Diagnostic, Diagnostics};
133use techy::source::{Source, SourceSpan};
134
135use crate::model::addr::{NodeAddr, TreeId};
136use crate::model::doc::Doc;
137use crate::model::names::{CapName, StageName};
138use crate::model::options::{BindSite, OptionError, ResolvedOptions, validate_values};
139use crate::core::plan::{Plan, PlanWarning};
140use crate::core::registry::StageKind;
141use crate::core::registry::frozen::StageIdx;
142use crate::core::run::cx::{
143 IgnoredPreference, PreferredRuleNotCandidate, PreferredRuleSetAside, RewriteCx, RunView,
144 StageCx, UncheckedOutput,
145};
146use crate::core::run::externals::{Externals, Stamp};
147use crate::core::run::order::RunOrder;
148use crate::core::stage::{Scope, TreesTable};
149use crate::core::data::store::{
150 AccessError, Computed, ComputedView, FoldTarget, StageOut, StoreError, fold_outs,
151};
152use crate::core::data::table::{TableId, TableKey};
153use crate::lang::guard;
154use crate::lang::{Flm, FlmDiagnostic, FlmDiagnostics, FlmOrigin, FlmSource};
155use crate::progress::{self, Kind, Pending, Unit};
156
157/// The kind of the run's row that counts the trees the rewrite stages run
158/// over.
159pub const REWRITES_KIND: Kind = Kind::new("flm.run.rewrites");
160
161/// How a run executes: on one thread or on several, whether the error gate may
162/// stop it, and how many diagnostics it keeps.
163///
164/// The error gate stops a run that has recorded an Error diagnostic, from
165/// parsing or from the stages, before the first batch that holds a stage with
166/// effects outside the store ([`Effect::Io`](crate::core::stage::Effect::Io);
167/// [`Plan::first_io_batch`](crate::core::plan::Plan::first_io_batch)), unless
168/// [`continue_with_errors`](RunOptions::continue_with_errors) is set. A run
169/// that the error gate stopped ends with the outcome
170/// [`RunOutcome::HaltedAtGate`] ([`Run::outcome`]). Apart from the error gate,
171/// these options do not change what is computed.
172///
173/// Pass the same options to every [`Run::step`]; [`Run::execute`] passes them
174/// to each step it takes.
175#[derive(Debug, Clone, Default, PartialEq, Eq)]
176pub struct RunOptions {
177 /// Runs all the work on one thread, even when the Cargo feature `parallel`
178 /// of `flm-core` is compiled in.
179 ///
180 /// The result is the same either way. The sequential path is always
181 /// compiled, and it is the only one when `flm-core` is built without its
182 /// default Cargo features.
183 pub sequential: bool,
184 /// Runs the stages with effects outside the store even when the run has
185 /// recorded Error diagnostics, instead of stopping at the error gate.
186 pub continue_with_errors: bool,
187 /// The number of diagnostics that the run keeps of those it produces
188 /// (the parse diagnostics have their own limit, set when parsing with
189 /// [`ParseOptions`](crate::lang::ParseOptions)). `None` keeps the parser
190 /// toolkit's default limit
191 /// ([`Diagnostics::DEFAULT_LIMIT`](techy::error::Diagnostics::DEFAULT_LIMIT)).
192 ///
193 /// Diagnostics past the limit are counted but not kept;
194 /// [`DiagnosticsView::any_recorded`], [`DiagnosticsView::has_errors`] and
195 /// [`DiagnosticsView::error_count`] count them. The run reads this value
196 /// from the options of the first step only.
197 pub max_diagnostics: Option<usize>,
198}
199
200impl RunOptions {
201 /// Creates the default options: parallel when `flm-core` is built with the
202 /// Cargo feature `parallel`, stopping at the error gate, and the parser
203 /// toolkit's default diagnostic limit.
204 pub fn new() -> RunOptions {
205 RunOptions::default()
206 }
207
208 /// Creates the default options, except that all the work runs on one
209 /// thread.
210 pub fn sequential() -> RunOptions {
211 RunOptions { sequential: true, ..RunOptions::default() }
212 }
213}
214
215/// What one call of [`Run::step`] reports.
216#[derive(Debug, Clone, Copy, PartialEq, Eq)]
217pub enum Step {
218 /// A step ran, and more steps remain.
219 More,
220 /// The run is over: it finished, stopped at the error gate, or was
221 /// cancelled ([`Run::outcome`]).
222 Done,
223}
224
225/// How a run ended, as [`Run::execute`] and [`Run::outcome`] report it.
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub enum RunOutcome {
228 /// The run executed every step of its plan.
229 Finished,
230 /// The error gate stopped the run before the first batch that holds a
231 /// stage with effects outside the store, because the run had recorded an
232 /// Error diagnostic ([`RunOptions::continue_with_errors`]).
233 HaltedAtGate,
234 /// The build was cancelled through the progress sheet that the run
235 /// reports on ([`Run::with_progress`]): the step under way produced
236 /// nothing, and the steps completed before it stay readable.
237 Cancelled,
238}
239
240/// The reason why a run could not be constructed, or could not go on.
241///
242/// Apart from [`DocumentOption`](RunError::DocumentOption), which reports an
243/// option value set on the document where it may not be set, none of these
244/// errors concerns the document's content: a problem with the content is
245/// reported as a diagnostic. A `RunError` means that the run was asked for
246/// something it cannot do. [`Run::new`] returns every variant except
247/// [`Worker`](RunError::Worker), which [`Run::step`] and [`Run::execute`]
248/// return together with [`Store`](RunError::Store).
249#[derive(Debug, Clone)]
250pub enum RunError {
251 /// The document sets a value for an option type that is not bound at
252 /// document level ([option types and values](crate::model::options)).
253 DocumentOption(OptionError),
254 /// The plan needs an external table for which no value is installed.
255 MissingExternal {
256 /// The name of the table.
257 table: CapName,
258 /// The table's description
259 /// ([`TableDef::docs`](crate::core::data::table::TableDef::docs)),
260 /// which says what belongs in it.
261 docs: String,
262 },
263 /// A value is installed for a table that the registry does not declare.
264 UnknownExternal {
265 /// The table name given with the installed value.
266 table: CapName,
267 /// The names of every external table that the registry declares.
268 roster: Vec<CapName>,
269 },
270 /// A value is installed for a table that is not declared as external
271 /// ([`FeatureBuilder::external_table`](crate::core::registry::FeatureBuilder::external_table));
272 /// only an external table can receive an installed value.
273 NotExternal {
274 /// The name of the table.
275 table: CapName,
276 },
277 /// An installed value is not of the value type that the table is declared
278 /// with.
279 ExternalType {
280 /// The name of the table.
281 table: CapName,
282 /// The short name of the declared value type.
283 declared: &'static str,
284 /// The short name of the type of the installed value.
285 installed: &'static str,
286 },
287 /// An installed value was produced under another registry, other rewrite
288 /// stages or other option values than this run uses; see [`Stamp`].
289 StampMismatch {
290 /// The name of the table.
291 table: CapName,
292 /// The stamp of the installed value.
293 installed: Stamp,
294 /// The stamp of this run.
295 expected: Stamp,
296 },
297 /// No worker thread could be created to run the work on.
298 Worker {
299 /// The error message of the failed thread creation.
300 detail: String,
301 },
302 /// An invariant of the store failed, for example a table written twice.
303 /// This reports a defect in the runner or in a stage, never a problem with
304 /// the document.
305 Store(StoreError),
306}
307
308impl fmt::Display for RunError {
309 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
310 match self {
311 RunError::DocumentOption(error) => fmt::Display::fmt(error, f),
312 RunError::MissingExternal { table, docs } => {
313 write!(f, "the plan needs the external table `{table}`, but no value is installed for it")?;
314 // A registry built without the cargo feature `docs` keeps no
315 // description of the table.
316 if !docs.is_empty() {
317 write!(f, "; the table holds: {docs}")?;
318 }
319 Ok(())
320 }
321 RunError::UnknownExternal { table, roster } => write!(
322 f,
323 "a value is installed for the table `{table}`, but no feature declares a table \
324 of that name; declared external tables: [{}]",
325 roster.iter().map(|n| n.as_str()).collect::<Vec<_>>().join(", ")
326 ),
327 RunError::NotExternal { table } => {
328 write!(
329 f,
330 "table `{table}` is not declared as an external table, so it cannot receive \
331 an installed value"
332 )
333 }
334 RunError::ExternalType { table, declared, installed } => write!(
335 f,
336 "the value installed for table `{table}` has type `{installed}`, but the table is \
337 declared with value type `{declared}`"
338 ),
339 RunError::StampMismatch { table, installed, expected } => write!(
340 f,
341 "the value installed for table `{table}` was produced under another registry, \
342 other rewrite stages or other option values than this run: ({installed}) \
343 instead of ({expected})"
344 ),
345 RunError::Worker { detail } => {
346 write!(f, "no thread could be created to execute the run: {detail}")
347 }
348 RunError::Store(error) => fmt::Display::fmt(error, f),
349 }
350 }
351}
352
353impl std::error::Error for RunError {}
354
355impl From<StoreError> for RunError {
356 fn from(error: StoreError) -> RunError {
357 RunError::Store(error)
358 }
359}
360
361/// What the rewrites did to one tree: the tree after each rewrite, in the
362/// plan's order and `None` from the first failure onwards, and everything the
363/// rewrites reported.
364type RewriteOuts = (Vec<Option<Arc<NodeTree<Flm>>>>, FlmDiagnostics);
365
366/// How far a run has got.
367#[derive(Debug, Clone, Copy, PartialEq, Eq)]
368enum Phase {
369 Rewrites,
370 Batch(usize),
371 Done(RunOutcome),
372}
373
374/// A run is one execution of one plan over one document; it owns the frozen
375/// trees, the store and the diagnostics.
376///
377/// Because a run owns everything it
378/// computes, one document may be run several times, under different plans,
379/// without one run seeing another's results.
380///
381/// Construct a run with [`Run::new`], give it the scope of a progress sheet
382/// with [`Run::with_progress`] if it reports on one, then [`Run::execute`] it
383/// to the end or [`Run::step`] through it. Read what it computed with [`Run::table`],
384/// [`Run::frozen_tree`] and [`Run::diagnostics`]. The [module
385/// documentation](self) describes what happens in between; [reading
386/// results](crate::guide::embedding#reading-results) shows how an embedding
387/// program reads an output.
388///
389/// # Examples
390///
391/// ```
392/// use std::sync::Arc;
393/// use flm_core::model::doc::{Doc, DocContent, FragmentLayout};
394/// use flm_core::core::plan::{Overrides, Plan};
395/// use flm_core::core::registry::{PackageEntry, RegistryBuilder, RegistryInputs};
396/// use flm_core::core::run::{Externals, Run, RunOptions, RunOutcome};
397/// use flm_core::lang::{parse_fragment, FlmOrigin, FlmSource, ParseOptions};
398/// use flm_core::stdlib::backends::text::TEXT_DOCUMENT;
399/// use flm_core::stdlib::{self, StdlibConfig};
400///
401/// let mut builder = RegistryBuilder::new();
402/// builder.use_package(stdlib::add_features(PackageEntry::new("std"), StdlibConfig::new()));
403/// builder.use_package(flm_core::math_passthrough::package());
404/// let registry = Arc::new(builder.build(&RegistryInputs::new())?);
405///
406/// let source = Arc::new(
407/// FlmSource::new("Hello \\textbf{world}.").with_origin(FlmOrigin::new("hello.flm")),
408/// );
409/// let fragment = parse_fragment(
410/// registry.lang(), source, FragmentLayout::default(), &ParseOptions::default(),
411/// )?;
412/// let mut content = DocContent::new();
413/// content.place(Arc::new(fragment));
414/// let doc = Arc::new(Doc::new(content));
415///
416/// let plan = Arc::new(Plan::for_workflow(®istry, "text", &Overrides::none())?);
417/// let mut run = Run::new(doc, plan, Externals::none())?;
418/// let outcome = run.execute(&RunOptions::new())?;
419///
420/// assert_eq!(outcome, RunOutcome::Finished);
421/// let artifacts = run.table(TEXT_DOCUMENT)?.expect("the text workflow writes it");
422/// let bytes = artifacts.entry().and_then(|a| a.as_bytes()).expect("one entry artifact");
423/// assert_eq!(String::from_utf8_lossy(bytes).trim_end(), "Hello world.");
424/// # Ok::<(), Box<dyn std::error::Error>>(())
425/// ```
426pub struct Run {
427 doc: Arc<Doc>,
428 plan: Arc<Plan>,
429 computed: Computed,
430 diagnostics: FlmDiagnostics,
431 frozen: BTreeMap<TreeId, Arc<NodeTree<Flm>>>,
432 /// The run's document order, computed when the rewrites are over; empty
433 /// before.
434 order: RunOrder,
435 tree_index: BTreeMap<usize, TreeId>,
436 options: BTreeMap<StageIdx, Arc<ResolvedOptions>>,
437 phase: Phase,
438 plan_source: Arc<FlmSource>,
439 sink_sized: bool,
440 /// The scope under which the run reports: [`progress::Scope::none`]
441 /// until [`Run::with_progress`] gives one.
442 progress: progress::Scope,
443 /// The run's row for the rewrite stages, declared and not yet started.
444 rewrites_row: Option<Pending>,
445 /// The row of each scheduled stage not yet started.
446 stage_rows: BTreeMap<StageIdx, Pending>,
447}
448
449impl Run {
450 /// Constructs a run of `plan` over `doc`, with the values of `externals`
451 /// installed into their external tables.
452 ///
453 /// Nothing is executed here: this checks the inputs and resolves the
454 /// option values of every scheduled stage, so that every constructed run
455 /// has sound inputs. The [module documentation](self) lists the checks.
456 /// Execute the run with [`Run::execute`] or [`Run::step`].
457 ///
458 /// # Errors
459 ///
460 /// Returns [`RunError::DocumentOption`] when the document sets a value for
461 /// an option type that is not bound at document level, and
462 /// [`RunError::MissingExternal`], [`RunError::UnknownExternal`],
463 /// [`RunError::NotExternal`], [`RunError::ExternalType`] or
464 /// [`RunError::StampMismatch`] for a problem with the installs.
465 pub fn new(doc: Arc<Doc>, plan: Arc<Plan>, externals: Externals) -> Result<Run, RunError> {
466 let registry = plan.registry();
467 let option_roster: Vec<_> = registry.options().keys().cloned().collect();
468 if let Some(error) = validate_values(
469 doc.options(),
470 BindSite::Document,
471 |key| registry.option_decl(key),
472 &option_roster,
473 None,
474 )
475 .into_iter()
476 .next()
477 {
478 return Err(RunError::DocumentOption(error));
479 }
480
481 let mut options: BTreeMap<StageIdx, Arc<ResolvedOptions>> = BTreeMap::new();
482 for idx in plan.rewrites().iter().chain(plan.order()) {
483 let stage_plan = plan.manifest(*idx).expect("a scheduled stage has a manifest");
484 let resolved = ResolvedOptions::resolve(
485 registry.stage(*idx).name.clone(),
486 &stage_plan.options,
487 &plan.request().render_options,
488 doc.options(),
489 );
490 options.insert(*idx, Arc::new(resolved));
491 }
492 let expected = stamp_of(&plan, &options);
493
494 let mut computed = Computed::new();
495 let roster: Vec<CapName> = registry.external_tables().map(|t| t.def.name.clone()).collect();
496 for (name, install) in externals.iter() {
497 let Some(entry) = registry.table_named(name) else {
498 return Err(RunError::UnknownExternal {
499 table: name.clone(),
500 roster: roster.clone(),
501 });
502 };
503 if !entry.external {
504 return Err(RunError::NotExternal { table: name.clone() });
505 }
506 if entry.def.ty.type_id() != install.table.type_id {
507 return Err(RunError::ExternalType {
508 table: name.clone(),
509 declared: entry.def.ty.short_name(),
510 installed: install.table.short_type_name(),
511 });
512 }
513 if let Some(stamp) = &install.stamp {
514 if *stamp != expected {
515 return Err(RunError::StampMismatch {
516 table: name.clone(),
517 installed: stamp.clone(),
518 expected: expected.clone(),
519 });
520 }
521 }
522 computed.install(entry.id, Arc::clone(&install.value))?;
523 }
524 for id in plan.externals() {
525 if !computed.contains(*id) {
526 let entry = registry.table(*id);
527 return Err(RunError::MissingExternal {
528 table: entry.def.name.clone(),
529 docs: entry.def.docs.clone(),
530 });
531 }
532 }
533
534 Ok(Run {
535 doc,
536 plan,
537 computed,
538 diagnostics: FlmDiagnostics::new(),
539 frozen: BTreeMap::new(),
540 order: RunOrder::default(),
541 tree_index: BTreeMap::new(),
542 options,
543 phase: Phase::Rewrites,
544 plan_source: Arc::new(Source::new("").with_origin(FlmOrigin::none())),
545 sink_sized: false,
546 progress: progress::Scope::none(),
547 rewrites_row: None,
548 stage_rows: BTreeMap::new(),
549 })
550 }
551
552 /// Gives the run the scope of a progress sheet under which it reports,
553 /// and declares the run's rows under it, so that a host sees what is to
554 /// come. Call it before the first step; a run that is given no scope
555 /// reports under [`progress::Scope::none`].
556 ///
557 /// The rows, in this order:
558 ///
559 /// - one row of kind `flm.run.rewrites`, counted in items: the trees the
560 /// rewrite stages run over. It starts when the rewrite stages begin and
561 /// advances as each tree is done;
562 /// - one row for each scheduled stage, in the plan's order, whose kind is
563 /// the stage's name. It starts when the stage's first call begins and
564 /// ends when its last call returns. The row of a per-tree stage is
565 /// counted in items, the trees of the run, and advances as each call
566 /// returns; the row of a document-scope stage has no count.
567 ///
568 /// The row of a stage that the error gate keeps from running, or that a
569 /// cancellation keeps from starting, ends as not run. The row of a stage
570 /// that panics, and every row running when the build is cancelled, ends
571 /// as failed. A row is declared only for what the run has still to do:
572 /// given after a step, the scope receives no row for that step.
573 ///
574 /// The run reads the sheet's cancellation through this scope; the
575 /// [module documentation](self#progress-and-cancellation) lists where.
576 pub fn with_progress(mut self, scope: progress::Scope) -> Run {
577 let plan = Arc::clone(&self.plan);
578 let registry = plan.registry();
579 let first_batch = match self.phase {
580 Phase::Rewrites => 0,
581 Phase::Batch(index) => index,
582 Phase::Done(_) => plan.batches().len(),
583 };
584 let first_stage = plan.batches().get(first_batch).map_or(plan.order().len(), |r| r.start);
585 self.rewrites_row =
586 matches!(self.phase, Phase::Rewrites).then(|| scope.child(&REWRITES_KIND, None));
587 self.stage_rows = plan.order()[first_stage..]
588 .iter()
589 .filter(|idx| matches!(registry.stage(**idx).kind, StageKind::Pipeline(_)))
590 .map(|idx| {
591 let kind = Kind::shared(registry.stage(*idx).name.name().clone());
592 (*idx, scope.child(&kind, None))
593 })
594 .collect();
595 self.progress = scope;
596 self
597 }
598
599 /// The document being processed.
600 pub fn doc(&self) -> &Arc<Doc> {
601 &self.doc
602 }
603
604 /// The plan being run.
605 pub fn plan(&self) -> &Arc<Plan> {
606 &self.plan
607 }
608
609 /// Returns the store: the values installed into external tables, and the
610 /// tables that the steps run so far have produced.
611 ///
612 /// [`Run::table`] reads one table of it, typed.
613 pub fn computed(&self) -> &Computed {
614 &self.computed
615 }
616
617 /// Reads one table of the store through a typed table key.
618 ///
619 /// `Ok(None)` means that no value of the table is present yet: no stage of
620 /// the plan writes it, or the batch that writes it has not run yet.
621 ///
622 /// Unlike a stage's read, this read is not restricted to declared reads: a
623 /// caller may read any table of the registry.
624 ///
625 /// # Errors
626 ///
627 /// Returns [`AccessError::UndeclaredRead`] when the registry declares no
628 /// table of that name (the error then gives `_host` as the stage and every
629 /// table of the registry as the declared reads), and
630 /// [`AccessError::TypeMismatch`] when the value type of `key` is not the
631 /// table's declared value type.
632 pub fn table<K: TableKey>(&self, key: K) -> Result<Option<&K::Table>, AccessError> {
633 let table = key.table_ref();
634 let host: StageName = StageName::from(crate::core::registry::HOST_FEATURE);
635 let Some(entry) = self.plan.registry().table_named(&table.name) else {
636 return Err(AccessError::UndeclaredRead {
637 stage: host,
638 table: table.name.clone(),
639 declared: self
640 .plan
641 .registry()
642 .tables()
643 .iter()
644 .map(|t| t.def.name.clone())
645 .collect(),
646 });
647 };
648 if entry.def.ty.type_id() != table.type_id {
649 return Err(AccessError::TypeMismatch {
650 stage: host,
651 table: table.name.clone(),
652 declared: entry.def.ty.short_name(),
653 requested: table.short_type_name(),
654 });
655 }
656 Ok(self.computed.get_as::<K::Table>(entry.id))
657 }
658
659 /// Returns the frozen tree of one of the document's trees: what the tree
660 /// became after the last rewrite stage.
661 ///
662 /// `None` before the rewrite stages have run, for a tree whose rewrite
663 /// failed, for a tree that the run's walk does not reach
664 /// ([`Run::tree_order`]), and for an identifier that the document does not
665 /// use.
666 pub fn frozen_tree(&self, id: TreeId) -> Option<&Arc<NodeTree<Flm>>> {
667 self.frozen.get(&id)
668 }
669
670 /// Returns the run's trees, each with its frozen tree, in the run's order
671 /// of the trees ([`Run::tree_order`]).
672 pub fn frozen_trees(&self) -> impl Iterator<Item = (TreeId, &Arc<NodeTree<Flm>>)> + '_ {
673 self.order.trees().iter().filter_map(|id| self.frozen.get(id).map(|tree| (*id, tree)))
674 }
675
676 /// Returns the run's trees in the run's order of the trees: the trees that
677 /// the document's walk, applied to the frozen trees, reaches, in the order
678 /// in which it enters them. Empty before the rewrite stages have run.
679 ///
680 /// A tree that the walk does not reach is not a tree of the run: a rewrite
681 /// stage removed its placing node (for example, a user definition whose
682 /// template does not use the argument that held it), or the tree that
683 /// includes it failed its rewrite. Its content is dropped with the node
684 /// that placed it, and no diagnostic reports it.
685 ///
686 /// A placed tree is entered at the node that places it, so its nodes come
687 /// in the middle of the tree that places it: this order says which tree
688 /// comes first, not which node. Document order across trees is the order
689 /// of the walk ([`StageCx::walk`](crate::core::run::StageCx::walk)).
690 pub fn tree_order(&self) -> &[TreeId] {
691 self.order.trees()
692 }
693
694 /// Returns every node of every tree of the run, in document order, with
695 /// its address: the order of [`StageCx::walk`](crate::core::run::StageCx::walk),
696 /// the document's walk applied to the frozen trees, a placed tree entered
697 /// at the node that places it. Empty before the rewrite stages have run.
698 ///
699 /// A host that reads the run's tables after the run, keyed by the
700 /// addresses of the frozen trees (a reference point's, for instance),
701 /// finds the nodes they name here; the trees of [`Run::doc`] are the trees
702 /// as parsed, before the rewrites.
703 pub fn walk(&self) -> impl Iterator<Item = (NodeAddr, NodeRef<'_, Flm>)> + '_ {
704 self.order.walk().iter().filter_map(|addr| {
705 let node = self.frozen.get(&addr.tree)?.get(addr.node)?;
706 Some((*addr, node))
707 })
708 }
709
710 /// Returns only the diagnostics that the run produced, without the parse
711 /// diagnostics.
712 ///
713 /// [`Run::diagnostics`] is usually what a caller wants: it returns both.
714 pub fn pipeline_diagnostics(&self) -> &FlmDiagnostics {
715 &self.diagnostics
716 }
717
718 /// Returns every diagnostic of the run: each fragment's parse diagnostics,
719 /// in the order in which the document's walk reaches the fragments and
720 /// once per fragment, then the diagnostics that the run produced.
721 pub fn diagnostics(&self) -> DiagnosticsView<'_> {
722 DiagnosticsView { doc: &self.doc, pipeline: &self.diagnostics }
723 }
724
725 /// Returns this run's stamp: the registry digest, the rewrite stages it
726 /// runs, and a digest of the option values those rewrite stages read.
727 ///
728 /// To install a value that this run produced into an external table of
729 /// another run, pass this stamp to [`Externals::install`]; the other run
730 /// checks it. See [`Stamp`].
731 pub fn stamp(&self) -> Stamp {
732 stamp_of(&self.plan, &self.options)
733 }
734
735 /// Whether the run is over: it finished, stopped at the error gate, or
736 /// was cancelled.
737 pub fn is_done(&self) -> bool {
738 matches!(self.phase, Phase::Done(_))
739 }
740
741 /// How the run ended, once it is over; `None` while steps remain.
742 pub fn outcome(&self) -> Option<RunOutcome> {
743 match self.phase {
744 Phase::Done(outcome) => Some(outcome),
745 Phase::Rewrites | Phase::Batch(_) => None,
746 }
747 }
748
749 /// Ends the run with `outcome`. The rows of the work not started end as
750 /// not run.
751 fn end(&mut self, outcome: RunOutcome) {
752 self.phase = Phase::Done(outcome);
753 self.rewrites_row = None;
754 self.stage_rows.clear();
755 }
756
757 /// Runs one step: the rewrite stages on the first call, then one batch of
758 /// the plan per call, in order.
759 ///
760 /// Returns [`Step::More`] while more steps remain and [`Step::Done`] once
761 /// the run is over; calling it again after that does nothing and returns
762 /// [`Step::Done`]. Before the first batch that holds a stage with effects
763 /// outside the store, the error gate may end the run (see
764 /// [`RunOptions`]). A build cancelled through the run's progress sheet
765 /// ends the run, and the step under way produces nothing
766 /// ([progress and cancellation](self#progress-and-cancellation)). The first call also sets the diagnostic limit from
767 /// [`RunOptions::max_diagnostics`]. Stepping changes only when the work
768 /// happens, never what is computed.
769 ///
770 /// # Errors
771 ///
772 /// Returns [`RunError::Worker`] when no thread could be created to run the
773 /// batch on, and [`RunError::Store`] when an invariant of the store failed.
774 ///
775 /// # Panics
776 ///
777 /// A stage or a rewrite stage that panics propagates the panic out of this
778 /// call. A panic means a defect in that stage; a problem with the document
779 /// is reported as a diagnostic. The whole batch is collected before
780 /// anything is folded into the store, so when a panic propagates, the store
781 /// is untouched and the run has not advanced.
782 pub fn step(&mut self, options: &RunOptions) -> Result<Step, RunError> {
783 if !self.sink_sized {
784 if let Some(limit) = options.max_diagnostics {
785 self.diagnostics = Diagnostics::with_limit(limit);
786 }
787 self.sink_sized = true;
788 }
789 match self.phase {
790 Phase::Done(_) => return Ok(Step::Done),
791 Phase::Rewrites | Phase::Batch(_) if self.progress.cancelled() => {
792 self.end(RunOutcome::Cancelled);
793 return Ok(Step::Done);
794 }
795 Phase::Rewrites => {
796 if !self.on_worker(options, |run| run.run_rewrites(options))? {
797 self.end(RunOutcome::Cancelled);
798 } else if self.plan.batches().is_empty() {
799 self.end(RunOutcome::Finished);
800 } else {
801 self.phase = Phase::Batch(0);
802 }
803 }
804 Phase::Batch(index) => {
805 if self.plan.first_io_batch() == Some(index)
806 && !options.continue_with_errors
807 && self.diagnostics().has_errors()
808 {
809 self.end(RunOutcome::HaltedAtGate);
810 } else if !self.on_worker(options, |run| run.run_batch(index, options))? {
811 self.end(RunOutcome::Cancelled);
812 } else if index + 1 < self.plan.batches().len() {
813 self.phase = Phase::Batch(index + 1);
814 } else {
815 self.end(RunOutcome::Finished);
816 }
817 }
818 }
819 Ok(if self.is_done() { Step::Done } else { Step::More })
820 }
821
822 /// Runs every remaining step, and returns how the run ended.
823 ///
824 /// # Errors
825 ///
826 /// The same as [`Run::step`], which this calls until the run is over.
827 ///
828 /// # Panics
829 ///
830 /// A stage or a rewrite stage that panics propagates the panic out of this
831 /// call; see [`Run::step`].
832 pub fn execute(&mut self, options: &RunOptions) -> Result<RunOutcome, RunError> {
833 while self.step(options)? == Step::More {}
834 Ok(self.outcome().expect("a run whose step returned `Done` is over"))
835 }
836
837 /// Runs `f` on a worker thread: a thread of the runner's pool on the
838 /// parallel path; otherwise the current thread when it is marked as a
839 /// worker thread, and a thread created for `f` when it is not.
840 fn on_worker<T: Send>(
841 &mut self,
842 options: &RunOptions,
843 f: impl FnOnce(&mut Run) -> Result<T, RunError> + Send,
844 ) -> Result<T, RunError> {
845 #[cfg(feature = "parallel")]
846 {
847 if !options.sequential {
848 let pool = pool()?;
849 return pool.install(move || f(self));
850 }
851 }
852 let _ = options;
853 match guard::on_worker_thread(move || f(self)) {
854 Ok(result) => result,
855 Err(error) => Err(RunError::Worker { detail: error.to_string() }),
856 }
857 }
858
859 /// Runs every rewrite over every tree, publishes each rewrite's table, and
860 /// records the frozen tree of each tree that came through. See the module
861 /// documentation.
862 ///
863 /// Returns `false`, having changed nothing, when the build was cancelled.
864 fn run_rewrites(&mut self, options: &RunOptions) -> Result<bool, RunError> {
865 let plan = Arc::clone(&self.plan);
866 let registry = plan.registry();
867 let rewrites: Vec<StageIdx> = plan.rewrites().to_vec();
868 let doc = Arc::clone(&self.doc);
869 let content = doc.content();
870 let inputs: Vec<(TreeId, Arc<NodeTree<Flm>>, crate::model::doc::FragmentLayout)> =
871 content
872 .walk_trees()
873 .filter_map(|id| {
874 content
875 .fragment(id)
876 .map(|fragment| (id, Arc::clone(fragment.tree()), fragment.layout()))
877 })
878 .collect();
879 let stage_options = &self.options;
880 let progress = &self.progress;
881 let row = self
882 .rewrites_row
883 .take()
884 .unwrap_or_else(no_row)
885 .start_counted(Unit::Items, inputs.len() as u64);
886 // `None` when a tree was skipped, because the build was cancelled.
887 let results: Option<Vec<RewriteOuts>> = map_indexed(inputs.len(), options, |i| {
888 if progress.cancelled() {
889 return None;
890 }
891 let (id, tree, layout) = &inputs[i];
892 let mut local = FlmDiagnostics::new();
893 let mut outs: Vec<Option<Arc<NodeTree<Flm>>>> = Vec::with_capacity(rewrites.len());
894 let mut current = Arc::clone(tree);
895 for idx in &rewrites {
896 let entry = registry.stage(*idx);
897 let StageKind::Rewrite(stage) = &entry.kind else { continue };
898 let cx = RewriteCx::new(registry, *id, *layout, &stage_options[idx]);
899 match stage.rewrite(*id, ¤t, &cx, &mut local) {
900 Ok(next) => {
901 outs.push(Some(Arc::clone(&next)));
902 current = next;
903 }
904 Err(error) => {
905 local.push(error.diagnostic().clone());
906 while outs.len() < rewrites.len() {
907 outs.push(None);
908 }
909 break;
910 }
911 }
912 }
913 row.advance(1);
914 Some((outs, local))
915 })
916 .into_iter()
917 .collect();
918 // On a cancelled build the row is dropped unfinished and ends as failed.
919 let (Some(results), false) = (results, progress.cancelled()) else {
920 return Ok(false);
921 };
922 row.finish();
923
924 for warning in plan.warnings() {
925 let span = SourceSpan::new(&self.plan_source, 0..0);
926 let diagnostic = match warning {
927 PlanWarning::PreferredRuleSetAside { backend, rule, unresolved, workflow } => {
928 Diagnostic::warning(
929 PreferredRuleSetAside {
930 rule: rule.to_string(),
931 backend: backend.to_string(),
932 unresolved: unresolved.iter().map(ToString::to_string).collect(),
933 workflow: workflow.as_ref().map(ToString::to_string),
934 },
935 span,
936 )
937 }
938 PlanWarning::PreferredRuleNotCandidate { backend, rule, workflow } => {
939 Diagnostic::warning(
940 PreferredRuleNotCandidate {
941 rule: rule.to_string(),
942 backend: backend.to_string(),
943 workflow: workflow.as_ref().map(ToString::to_string),
944 },
945 span,
946 )
947 }
948 PlanWarning::IgnoredPreference { stage, excluded_by, over, workflow } => {
949 Diagnostic::warning(
950 IgnoredPreference {
951 stage: stage.to_string(),
952 excluded_by: excluded_by.to_string(),
953 over: over.to_string(),
954 workflow: workflow.as_ref().map(ToString::to_string),
955 },
956 span,
957 )
958 }
959 PlanWarning::UncheckedOutput { backend, feature, written, reader, workflow } => {
960 Diagnostic::warning(
961 UncheckedOutput {
962 feature: feature.to_string(),
963 backend: backend.to_string(),
964 written: written.clone(),
965 reader: reader.clone(),
966 workflow: workflow.as_ref().map(ToString::to_string),
967 },
968 span,
969 )
970 }
971 };
972 self.diagnostics.push(diagnostic);
973 }
974
975 let mut tables: Vec<(TableId, TreesTable)> = rewrites
976 .iter()
977 .map(|idx| {
978 let table = registry
979 .stage(*idx)
980 .writes
981 .first()
982 .copied()
983 .expect("a rewrite writes its trees table");
984 (table, TreesTable::default())
985 })
986 .collect();
987 for (i, (outs, local)) in results.into_iter().enumerate() {
988 let (id, tree, _) = &inputs[i];
989 let mut last: Option<Arc<NodeTree<Flm>>> = Some(Arc::clone(tree));
990 let mut failed = false;
991 for (position, out) in outs.into_iter().enumerate() {
992 match out {
993 Some(next) => {
994 tables[position].1.trees.insert(*id, Arc::clone(&next));
995 last = Some(next);
996 }
997 None => {
998 failed = true;
999 break;
1000 }
1001 }
1002 }
1003 if !failed {
1004 if let Some(tree) = last {
1005 self.tree_index.insert(Arc::as_ptr(&tree) as usize, *id);
1006 self.frozen.insert(*id, tree);
1007 }
1008 }
1009 for diagnostic in local {
1010 self.diagnostics.push(diagnostic);
1011 }
1012 }
1013 tables.sort_by_key(|(id, _)| *id);
1014 for (id, table) in tables {
1015 self.computed.install(id, Arc::new(table))?;
1016 }
1017 let (order, diags) = RunOrder::new(content, &self.frozen);
1018 // A tree the walk does not reach is not a tree of the run.
1019 self.frozen.retain(|id, _| order.has_tree(*id));
1020 self.tree_index.retain(|_, id| order.has_tree(*id));
1021 self.order = order;
1022 for diagnostic in diags {
1023 self.diagnostics.push(diagnostic);
1024 }
1025 Ok(true)
1026 }
1027
1028 /// Runs the stages of one batch and folds their pieces into the store. See
1029 /// the module documentation.
1030 ///
1031 /// Returns `false`, having changed nothing, when the build was cancelled.
1032 fn run_batch(&mut self, index: usize, options: &RunOptions) -> Result<bool, RunError> {
1033 let plan = Arc::clone(&self.plan);
1034 let registry = plan.registry();
1035 let range = plan.batches()[index].clone();
1036 let stages: Vec<StageIdx> = plan.order()[range].to_vec();
1037 let rows: Vec<(StageIdx, Pending)> = stages
1038 .iter()
1039 .map(|idx| (*idx, self.stage_rows.remove(idx).unwrap_or_else(no_row)))
1040 .collect();
1041 let base = self.computed.clone();
1042 let alive: Vec<TreeId> = self.order.trees().to_vec();
1043 let view = RunView {
1044 doc: &self.doc,
1045 registry,
1046 plan: &plan,
1047 frozen: &self.frozen,
1048 order: &self.order,
1049 tree_index: &self.tree_index,
1050 computed: &base,
1051 options: &self.options,
1052 };
1053 let progress = &self.progress;
1054 // `None` for a stage whose calls were not all made, because the build
1055 // was cancelled.
1056 let outs: Option<Vec<Vec<StageOut<'_>>>> = map_owned(rows, options, |(idx, row)| {
1057 let entry = registry.stage(idx);
1058 let StageKind::Pipeline(stage) = &entry.kind else { return Some(Vec::new()) };
1059 let stage_plan = plan.manifest(idx).expect("a scheduled stage has a manifest");
1060 if progress.cancelled() {
1061 return None;
1062 }
1063 match entry.decl.scope {
1064 Scope::PerTree => {
1065 let row = row.start_counted(Unit::Items, alive.len() as u64);
1066 let scope = row.scope();
1067 let outs: Option<Vec<StageOut<'_>>> = map_indexed(alive.len(), options, |j| {
1068 // The question before the first call was asked just
1069 // above, before the row started.
1070 if j > 0 && progress.cancelled() {
1071 return None;
1072 }
1073 let cx = StageCx::new(
1074 &view,
1075 idx,
1076 Some(alive[j]),
1077 ComputedView::new(&entry.name, &stage_plan.reads, &base),
1078 scope.clone(),
1079 );
1080 let mut out = StageOut::new(&entry.name, &stage_plan.writes);
1081 stage.run(&cx, &mut out);
1082 row.advance(1);
1083 Some(out)
1084 })
1085 .into_iter()
1086 .collect();
1087 // A row dropped unfinished ends as failed.
1088 if outs.is_some() && !progress.cancel_requested() {
1089 row.finish();
1090 }
1091 outs
1092 }
1093 Scope::Document => {
1094 let row = row.start();
1095 let cx = StageCx::new(
1096 &view,
1097 idx,
1098 None,
1099 ComputedView::new(&entry.name, &stage_plan.reads, &base),
1100 row.scope(),
1101 );
1102 let mut out = StageOut::new(&entry.name, &stage_plan.writes);
1103 stage.run(&cx, &mut out);
1104 if !progress.cancel_requested() {
1105 row.finish();
1106 }
1107 Some(vec![out])
1108 }
1109 }
1110 })
1111 .into_iter()
1112 .collect();
1113 // On a cancelled build, everything the batch produced is discarded.
1114 let (Some(outs), false) = (outs, progress.cancelled()) else {
1115 return Ok(false);
1116 };
1117 // The whole batch is collected before anything is folded in, so a stage
1118 // that panics leaves the store untouched and the run unadvanced.
1119 for (k, outs) in outs.into_iter().enumerate() {
1120 let idx = stages[k];
1121 let entry = registry.stage(idx);
1122 let stage_plan = plan.manifest(idx).expect("a scheduled stage has a manifest");
1123 fold_outs(
1124 &entry.name,
1125 &stage_plan.writes,
1126 outs,
1127 FoldTarget::Main,
1128 &mut self.computed,
1129 &mut self.diagnostics,
1130 )?;
1131 }
1132 Ok(true)
1133 }
1134}
1135
1136/// A declared row with nothing behind it, for work whose row the run did not
1137/// declare.
1138fn no_row() -> Pending {
1139 progress::Scope::none().child(&REWRITES_KIND, None)
1140}
1141
1142impl fmt::Debug for Run {
1143 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1144 f.debug_struct("Run")
1145 .field("phase", &self.phase)
1146 .field("frozen", &self.frozen.keys().collect::<Vec<_>>())
1147 .field("computed", &self.computed)
1148 .field("diagnostics", &self.diagnostics.len())
1149 .finish()
1150 }
1151}
1152
1153/// The stamp of a plan's registry, the rewrite stages it schedules, and the
1154/// values of the options those rewrite stages read.
1155fn stamp_of(plan: &Plan, options: &BTreeMap<StageIdx, Arc<ResolvedOptions>>) -> Stamp {
1156 let mut hasher = crate::model::digest::Fnv1a64::new();
1157 for idx in plan.rewrites() {
1158 hasher.write_u64(options[idx].digest());
1159 }
1160 Stamp {
1161 digest: plan.registry().digest(),
1162 active_rewrites: plan.rewrite_names(),
1163 option_reads: hasher.value(),
1164 }
1165}
1166
1167/// Applies `f` to every index below `n`, in parallel under the Cargo feature
1168/// `parallel` of `flm-core` when the options allow it.
1169///
1170/// The results always come back in index order, whichever path ran, so the
1171/// parallel and the sequential run produce the same output.
1172fn map_indexed<T, F>(n: usize, options: &RunOptions, f: F) -> Vec<T>
1173where
1174 T: Send,
1175 F: Fn(usize) -> T + Sync + Send,
1176{
1177 #[cfg(feature = "parallel")]
1178 {
1179 use rayon::prelude::*;
1180 if !options.sequential {
1181 return (0..n).into_par_iter().map(&f).collect();
1182 }
1183 }
1184 let _ = options;
1185 (0..n).map(&f).collect()
1186}
1187
1188/// Applies `f` to every item of `items`, as [`map_indexed`] does to every
1189/// index: in parallel when the options allow it, the results in the items'
1190/// order.
1191fn map_owned<I, T, F>(items: Vec<I>, options: &RunOptions, f: F) -> Vec<T>
1192where
1193 I: Send,
1194 T: Send,
1195 F: Fn(I) -> T + Sync + Send,
1196{
1197 #[cfg(feature = "parallel")]
1198 {
1199 use rayon::prelude::*;
1200 if !options.sequential {
1201 return items.into_par_iter().map(&f).collect();
1202 }
1203 }
1204 let _ = options;
1205 items.into_iter().map(&f).collect()
1206}
1207
1208/// The runner's thread pool, built the first time it is needed.
1209///
1210/// Its threads are created with
1211/// [`WORKER_STACK_SIZE`](guard::WORKER_STACK_SIZE) bytes of stack, and the
1212/// first action of each is to mark itself as a worker thread with this size
1213/// and the default reserved share, so
1214/// that guarded work never has to create a thread of its own.
1215#[cfg(feature = "parallel")]
1216fn pool() -> Result<&'static rayon::ThreadPool, RunError> {
1217 use std::sync::OnceLock;
1218 static POOL: OnceLock<Result<rayon::ThreadPool, String>> = OnceLock::new();
1219 let pool = POOL.get_or_init(|| {
1220 rayon::ThreadPoolBuilder::new()
1221 .stack_size(guard::WORKER_STACK_SIZE)
1222 .start_handler(|_| {
1223 guard::mark_worker_thread(guard::WorkerStack::new(guard::WORKER_STACK_SIZE))
1224 })
1225 .build()
1226 .map_err(|error| error.to_string())
1227 });
1228 match pool {
1229 Ok(pool) => Ok(pool),
1230 Err(detail) => Err(RunError::Worker { detail: detail.clone() }),
1231 }
1232}
1233
1234/// Every diagnostic of a run, as one sequence: each fragment's parse
1235/// diagnostics first, in the order in which the document's walk reaches the
1236/// fragments, then the diagnostics that the run produced.
1237///
1238/// Created by [`Run::diagnostics`]. A fragment placed in the document more
1239/// than once contributes its parse diagnostics once, at the first place the
1240/// walk reaches it, because they are facts about the text, not about a
1241/// placement. A diagnostic reports a problem with a document: a severity, a
1242/// position, and a typed condition with its data
1243/// ([diagnostics](crate::guide::concepts_overview#diagnostics)).
1244pub struct DiagnosticsView<'a> {
1245 doc: &'a Doc,
1246 pipeline: &'a FlmDiagnostics,
1247}
1248
1249impl<'a> DiagnosticsView<'a> {
1250 /// The document's fragments in the order the document's walk reaches
1251 /// them, each appearing once however many times it is placed.
1252 fn fragments(&self) -> Vec<&'a crate::model::doc::Fragment> {
1253 let content = self.doc.content();
1254 let mut seen: BTreeSet<usize> = BTreeSet::new();
1255 let mut fragments = Vec::new();
1256 for id in content.walk_trees() {
1257 if let Some(fragment) = content.fragment(id) {
1258 if seen.insert(Arc::as_ptr(fragment) as usize) {
1259 fragments.push(&**fragment);
1260 }
1261 }
1262 }
1263 fragments
1264 }
1265
1266 /// Returns every kept diagnostic, in order.
1267 pub fn iter(&self) -> impl Iterator<Item = &'a FlmDiagnostic> + 'a {
1268 let pipeline = self.pipeline;
1269 self.fragments()
1270 .into_iter()
1271 .flat_map(|fragment| fragment.diags().iter())
1272 .chain(pipeline.iter())
1273 }
1274
1275 /// The number of kept diagnostics.
1276 ///
1277 /// A run may record more diagnostics than it keeps (see
1278 /// [`RunOptions::max_diagnostics`]); the ones past the limit are not
1279 /// counted here. [`DiagnosticsView::any_recorded`] and
1280 /// [`DiagnosticsView::error_count`] do count them.
1281 pub fn retained_len(&self) -> usize {
1282 self.iter().count()
1283 }
1284
1285 /// Whether any diagnostic was reported, kept or not.
1286 pub fn any_recorded(&self) -> bool {
1287 self.fragments().iter().any(|fragment| !fragment.diags().is_empty())
1288 || !self.pipeline.is_empty()
1289 }
1290
1291 /// Whether any diagnostic of Error severity was reported, kept or not. The
1292 /// run's error gate checks this.
1293 pub fn has_errors(&self) -> bool {
1294 self.fragments().iter().any(|fragment| fragment.diags().has_errors())
1295 || self.pipeline.has_errors()
1296 }
1297
1298 /// The number of diagnostics of Error severity that were reported, kept or
1299 /// not.
1300 pub fn error_count(&self) -> usize {
1301 self.fragments().iter().map(|fragment| fragment.diags().error_count()).sum::<usize>()
1302 + self.pipeline.error_count()
1303 }
1304
1305 /// Renders every kept diagnostic as text, joined by line breaks; the
1306 /// diagnostics past the limit are not mentioned.
1307 pub fn render_all(&self) -> String {
1308 self.iter().map(|d| d.render()).collect::<Vec<_>>().join("\n")
1309 }
1310}
1311
1312impl fmt::Debug for DiagnosticsView<'_> {
1313 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1314 f.debug_list().entries(self.iter().map(|d| d.identifier().to_string())).finish()
1315 }
1316}