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