Skip to main content

flm_core/core/plan/
request.rs

1//! The input of plan building: the plan request, the changes a caller makes to a
2//! workflow's request, and the number that identifies a plan.
3//!
4//! - [`PlanRequest`] is everything a caller says about what it wants from a plan;
5//!   [`Plan::build`](crate::core::plan::Plan::build) builds the plan that satisfies
6//!   it.
7//! - [`Overrides`] are the changes a caller makes to the request of a registered
8//!   workflow. Most callers never write a plan request: they choose a workflow by
9//!   name and let [`Plan::for_workflow`](crate::core::plan::Plan::for_workflow)
10//!   build its request, with these changes applied.
11//! - [`PlanKey`] identifies a plan by everything it was built from, so that a
12//!   built plan can be cached and reused.
13//!
14//! A plan request holds nothing about any document. One plan therefore serves
15//! every document rendered the same way. See [`crate::core::plan`] for the whole
16//! process.
17use std::collections::BTreeMap;
18use std::fmt;
19
20use crate::model::names::{BackendName, CapName, ElementName, StageName, WorkflowName};
21use crate::model::options::OptionValues;
22use crate::core::registry::entities::LoweringSelection;
23
24/// A plan request: everything a caller says about what it wants from a plan.
25///
26/// To *demand* a capability is to ask the plan for a stage that provides it; the
27/// demands of a plan request are the capabilities it asks for, and a workflow is a
28/// named set of demands together with the choices that go with them
29/// ([`WorkflowDef`](crate::core::registry::WorkflowDef)). A capability is a
30/// registered dotted name for a state of processing that a stage brings about
31/// ([`CapabilityDef`](crate::core::registry::CapabilityDef)).
32///
33/// The request has five parts. The demands say what is wanted; the other four
34/// fields decide how: which stage provides a capability several stages
35/// provide, which lowering rule lowers an element several rules lower, which
36/// elements a backend need not render, and which option values the render
37/// request sets. These five fields, together with the registry,
38/// decide the whole plan. The same fields are therefore what a stage can consult
39/// while it states its needs ([`PlanCx`](crate::core::plan::PlanCx)), and what the
40/// [`PlanKey`] is computed over.
41///
42/// The request also records the workflow it was made from, if any
43/// ([`workflow`](PlanRequest#structfield.workflow)). Plan building does not
44/// consult that name; the errors and warnings of the plan name it, so that a
45/// person reading them knows which workflow's request they are about.
46///
47/// Create a request with [`PlanRequest::new`] and add to it with the methods that
48/// take and return it, or set the public fields directly. Build the plan with
49/// [`Plan::build`](crate::core::plan::Plan::build), which checks that every name
50/// in the request is registered. To start from a registered workflow instead, use
51/// [`workflow_request`](crate::core::plan::workflow_request) or
52/// [`Plan::for_workflow`](crate::core::plan::Plan::for_workflow).
53///
54/// # Examples
55///
56/// ```
57/// use flm_core::core::plan::PlanRequest;
58///
59/// let request = PlanRequest::new()
60///     .demand("flm.validated")
61///     .prefer("flm.blocks.structure");
62///
63/// assert_eq!(request.demands.len(), 1);
64/// ```
65#[derive(Debug, Clone, Default)]
66pub struct PlanRequest {
67    /// The demanded capabilities. A name here may also be a collection, a name
68    /// for a set of capabilities
69    /// ([`CollectionDef`](crate::core::registry::CollectionDef)): building the
70    /// plan replaces it with its members.
71    pub demands: Vec<CapName>,
72    /// The stages to schedule where several stages could provide one
73    /// capability, most preferred first. A preference for a stage that provides
74    /// nothing the plan needs schedules nothing. A preference for a stage that the
75    /// plan had to rule out becomes a
76    /// [`PlanWarning::IgnoredPreference`](crate::core::plan::PlanWarning::IgnoredPreference).
77    /// See [`selection`](crate::core::plan::selection) for how a provider is
78    /// chosen.
79    pub prefer: Vec<StageName>,
80    /// The lowering rules to use where several rules could lower one element,
81    /// per backend, each list most preferred first. See
82    /// [`SelectedRules`](crate::core::plan::SelectedRules) for how a rule is
83    /// chosen.
84    pub lowering: BTreeMap<BackendName, LoweringSelection>,
85    /// The accepted unrenderable elements, per backend.
86    ///
87    /// An accepted unrenderable element is an element the plan request lists, per
88    /// backend, as one the backend need not render: the plan builds anyway, and
89    /// each occurrence lowers to a childless `flm.pres.unsupported` node with one
90    /// Error diagnostic. Without this list, a backend that cannot render an element
91    /// a document may contain makes the plan build fail
92    /// ([`PlanError::Incomplete`](crate::core::plan::PlanError::Incomplete)).
93    pub unsupported: BTreeMap<BackendName, Vec<ElementName>>,
94    /// The option values set on the render request. An option type is a plain
95    /// Rust struct a feature declares once, with a binding that says where its
96    /// values may be set ([`crate::model::options`]). A value here for an option
97    /// type whose binding does not admit the render request makes the plan build
98    /// fail ([`PlanError::RenderOption`](crate::core::plan::PlanError::RenderOption)).
99    pub render_options: OptionValues,
100    /// The workflow the request was made from, or `None` for a request a
101    /// program builds by hand. [`workflow_request`](crate::core::plan::workflow_request)
102    /// sets it. Plan building does not consult it: the errors and warnings of
103    /// the plan name the workflow in their messages, and the [`PlanKey`] leaves
104    /// it out, so that two workflows that produce the same request share a plan.
105    pub workflow: Option<WorkflowName>,
106}
107
108impl PlanRequest {
109    /// Creates a plan request that demands nothing and decides nothing.
110    pub fn new() -> PlanRequest {
111        PlanRequest::default()
112    }
113
114    /// Adds `capability` to the demands, after the ones already there, and returns
115    /// the request. `capability` may also be the name of a collection, which
116    /// demands each of its members.
117    pub fn demand(mut self, capability: impl Into<CapName>) -> PlanRequest {
118        self.demands.push(capability.into());
119        self
120    }
121
122    /// Adds `stage` to the preferred stages, after the ones already there, and
123    /// returns the request.
124    pub fn prefer(mut self, stage: impl Into<StageName>) -> PlanRequest {
125        self.prefer.push(stage.into());
126        self
127    }
128
129    /// Sets the lowering rules preferred on `backend`, replacing any selection
130    /// already set for that backend, and returns the request.
131    pub fn lowering(
132        mut self,
133        backend: impl Into<BackendName>,
134        selection: LoweringSelection,
135    ) -> PlanRequest {
136        self.lowering.insert(backend.into(), selection);
137        self
138    }
139
140    /// Adds `element` to the accepted unrenderable elements of `backend` and
141    /// returns the request: the plan builds even though `backend` cannot render
142    /// `element`. See the [`unsupported`](PlanRequest#structfield.unsupported)
143    /// field.
144    pub fn unsupported(
145        mut self,
146        backend: impl Into<BackendName>,
147        element: impl Into<ElementName>,
148    ) -> PlanRequest {
149        self.unsupported.entry(backend.into()).or_default().push(element.into());
150        self
151    }
152
153    /// Sets the option values of the render request, replacing any already set,
154    /// and returns the request.
155    pub fn render_options(mut self, options: OptionValues) -> PlanRequest {
156        self.render_options = options;
157        self
158    }
159}
160
161/// The changes a caller makes to the plan request of a registered workflow.
162///
163/// A workflow ([`WorkflowDef`](crate::core::registry::WorkflowDef)) is a named
164/// set of demands together with the choices that go with them, held in the
165/// registry as a complete plan request.
166/// [`workflow_request`](crate::core::plan::workflow_request) turns it into a
167/// [`PlanRequest`] and then applies these changes, and
168/// [`Plan::for_workflow`](crate::core::plan::Plan::for_workflow) builds the result.
169/// Each field combines with the workflow's own value as its documentation below
170/// says, so that a caller adds to a workflow without restating it.
171///
172/// [`Overrides::none`] changes nothing.
173#[derive(Debug, Clone, Default)]
174pub struct Overrides {
175    /// Capabilities demanded in addition to the workflow's demands.
176    pub demands: Vec<CapName>,
177    /// Stages preferred before the ones the workflow prefers.
178    pub prefer: Vec<StageName>,
179    /// Lowering selections, per backend. The selection given here for a backend
180    /// replaces the workflow's whole selection for that backend; the workflow's
181    /// selections for other backends stay.
182    pub lowering: BTreeMap<BackendName, LoweringSelection>,
183    /// Accepted unrenderable elements, per backend, added to the ones the
184    /// workflow already accepts.
185    pub unsupported: BTreeMap<BackendName, Vec<ElementName>>,
186    /// Option values for the render request, applied one option type at a
187    /// time: a value given here for an option type replaces the workflow's value
188    /// for that type, and every other option type keeps the workflow's value.
189    pub render_options: OptionValues,
190}
191
192impl Overrides {
193    /// Creates overrides that change nothing about the workflow's request.
194    pub fn none() -> Overrides {
195        Overrides::default()
196    }
197}
198
199/// The number that identifies a plan, computed over everything the plan was built
200/// from.
201///
202/// The key is a digest of the registry's own digest, the demands (with
203/// collections replaced by their members), the preferred stages, the lowering
204/// selections, the accepted unrenderable elements and the option values of the
205/// render request: everything that plan building consults, and nothing else. The
206/// name of the workflow the request was made from is left out, since plan
207/// building does not consult it: two workflows that produce the same request
208/// share a plan. Two
209/// plan requests with the same key against the same registry therefore build the
210/// same plan, and a caller can cache a built plan under its key. Read a plan's key
211/// with [`Plan::key`](crate::core::plan::Plan::key).
212///
213/// The key is displayed as sixteen hexadecimal digits.
214#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
215pub struct PlanKey(
216    /// The digest. Only comparison between keys is meaningful; the value itself
217    /// carries no other information.
218    pub u64,
219);
220
221impl fmt::Debug for PlanKey {
222    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223        write!(f, "PlanKey({:016x})", self.0)
224    }
225}
226
227impl fmt::Display for PlanKey {
228    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229        write!(f, "{:016x}", self.0)
230    }
231}