Skip to main content

flm_core/model/
options.rs

1//! Option types: the typed values a feature lets a caller set on a document or
2//! on a render request, and how a stage reads them.
3//!
4//! An option type is a plain Rust struct a feature declares once. Its values
5//! are set on a document or on a render request, and the type's binding says
6//! which; a render request is the set of option values that a [plan
7//! request](crate::core::plan::PlanRequest) carries
8//! ([`PlanRequest::render_options`](crate::core::plan::PlanRequest::render_options())).
9//! A stage reads the value for an option type it declared a read of: the
10//! render value if one is set, otherwise the document value, otherwise the
11//! type's default. An **option value** is a value set for an option type.
12//! Option values differ from a feature's configuration, which is fixed when the
13//! registry is built (see [settings, options and
14//! configuration](crate::guide::concepts_overview#settings-options-and-configuration)).
15//!
16//! # Declaring an option type
17//!
18//! A feature declares an option type with
19//! [`FeatureBuilder::options`](crate::core::registry::FeatureBuilder::options)
20//! (or [`options_with_docs`](crate::core::registry::FeatureBuilder::options_with_docs)),
21//! giving its binding ([`Bind`]). The Rust type identifies the option type:
22//! options have no names of their own. A feature usually declares one struct
23//! per binding, and a feature with more options gives that struct more fields;
24//! it declares a second struct for values that must stay apart, such as values
25//! that only Rust code may set, declared without a settings key (the HTML
26//! backend's
27//! [`HtmlAllowedUrlSchemes`](crate::stdlib::backends::html::HtmlAllowedUrlSchemes)). Any
28//! type that implements `Default`, `Hash` and `Debug` and can be shared between
29//! threads can be an option type ([`Options`]).
30//!
31//! # Option types declared from data
32//!
33//! A feature whose settings are given as data rather than as Rust types (a
34//! feature written in a script, for example) declares its option types by name,
35//! with [`SettingsDecl::options_data`](crate::core::settings::SettingsDecl::options_data)
36//! (and its configuration with
37//! [`SettingsDecl::config_data`](crate::core::settings::SettingsDecl::config_data),
38//! named by the feature's name). Such an option type is identified by its name
39//! ([`OptionKey::Data`]), and its values are [`DataValue`]s, the data as
40//! written; its default is the empty map. Everything above holds for it alike:
41//! its binding, the resolution of a read, the three mistakes. A stage declares a
42//! read of one with
43//! [`Needs::option_named`](crate::core::stage::Needs::option_named) and reads it
44//! with [`StageCx::option_named`](crate::core::run::StageCx::option_named); a
45//! caller sets a value with [`OptionValues::set_named`].
46//!
47//! # Setting values and reading them
48//!
49//! A caller sets option values in an [`OptionValues`] collection, in one of two
50//! places: on the document, with
51//! [`Doc::with_options`](crate::model::doc::Doc::with_options), or on the render
52//! request, with
53//! [`PlanRequest::render_options`](crate::core::plan::PlanRequest::render_options()).
54//! The option type's [`Bind`] says which of the two places may set it.
55//!
56//! A stage, a rewrite stage or a lowering rule declares each option type it
57//! reads, with [`Needs::option`](crate::core::stage::Needs::option) or
58//! [`LoweringDecl::option`](crate::core::lowering::LoweringDecl::option).
59//! Before the stage runs, each declared read is resolved once into
60//! [`ResolvedOptions`]: the value set on the render request if there is one,
61//! otherwise the value set on the document if there is one, otherwise the
62//! type's [`Default`]. The stage then reads the value from its context, with
63//! [`StageCx::option`](crate::core::run::StageCx::option). The same rule
64//! applies everywhere, so no feature defines an order of its own.
65//!
66//! Three mistakes are reported as an [`OptionError`] rather than ignored:
67//!
68//! - reading an option type that the stage did not declare, reported when the
69//!   stage reads it;
70//! - setting a value for an option type in a place its binding does not admit,
71//!   or for an option type that no feature declares, reported when the values
72//!   are checked ([`validate_values`]): when a run is constructed, for the
73//!   values set on the document, and when a plan is built, for the values set
74//!   on the render request;
75//! - declaring a read of an option type whose binding is [`Bind::Registry`],
76//!   reported when a plan is built ([`OptionError::RegistryBoundRead`]).
77//!
78//! # Why reads and bindings are declared
79//!
80//! Because each stage declares the option types it reads, the library knows,
81//! without running anything, which option values a stage's output can depend
82//! on. The stamp of a run ([`Stamp`](crate::core::run::Stamp)), which records
83//! what the values the run produces were produced under, uses this: it holds a
84//! digest of the option values that the rewrite stages read
85//! ([`ResolvedOptions::digest`]), which is why every option type must
86//! implement [`Hash`]. Because each option type declares where its values are
87//! set, a plan depends only on the render option values of its plan request,
88//! whose digest is part of the plan's identity
89//! ([`PlanKey`](crate::core::plan::PlanKey)), and never on the values set on
90//! any one document.
91//!
92//! # Items
93//!
94//! - [`Bind`] and [`BindSite`] — the bindings, and the two places where values
95//!   are set.
96//! - [`Options`] — the requirements an option type meets; [`OptionKey`] — the
97//!   identifier of an option type, its Rust type or the name it was declared
98//!   under from data.
99//! - [`DataValue`] — the value of an option type declared from data;
100//!   [`hash_value`] — how such a value is hashed.
101//! - [`OptionDecl`] — a feature's declaration of an option type;
102//!   [`OptionRef`] — a stage's declaration that it reads one.
103//! - [`OptionValues`] — the values set in one place; [`validate_values`] —
104//!   checking them against the declarations.
105//! - [`ResolvedOptions`] — one stage's declared reads, resolved to values.
106//! - [`OptionError`] — every error about options.
107//! - [`TypeKey`] and [`short_type_name`] — the identifier of a Rust type, and
108//!   its short name as messages show it.
109//!
110//! # Position of this module
111//!
112//! This module is part of [`crate::model`], beside the document, rather than
113//! of [`crate::core`], which reads the values: a [`Doc`](crate::model::doc::Doc)
114//! holds the [`OptionValues`] set on it, so the document model would
115//! otherwise depend on the layer above it. This module itself uses only the
116//! names of [`crate::model::names`] and the hasher of [`crate::model::digest`].
117
118use std::any::{Any, TypeId};
119use std::collections::BTreeMap;
120use std::fmt;
121use std::hash::{Hash, Hasher};
122use std::sync::Arc;
123
124use serde_json::{Map, Value};
125
126use crate::model::names::{FeatureName, Name, StageName, WorkflowName};
127use crate::model::digest::{Fnv1a64, digest_of};
128
129/// The binding of an option type: where a value for it may be set, on the
130/// document, on the render request, on both, or nowhere.
131///
132/// A feature chooses the binding when it declares the option type, and the
133/// binding holds for every caller: a caller of the library never chooses one,
134/// and an option that must be settable in different places for different
135/// purposes is declared as two option types.
136/// [`Bind::admits`] says whether a binding lets a value be set in a given
137/// place ([`BindSite`]).
138///
139/// It is written to data with `Serialize`; see [serialized
140/// forms](crate::core::registry#serialized-forms).
141#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
142#[derive(serde::Serialize, schemars::JsonSchema)]
143#[serde(rename_all = "lowercase")]
144pub enum Bind {
145    /// Fixed when the registry is built: the value is part of the
146    /// configuration the feature was constructed with, and the feature holds
147    /// it. No value may be set on the document or on the render request, and
148    /// building a plan fails ([`OptionError::RegistryBoundRead`]) when a stage
149    /// declares a read of such a type, since the read could only return the
150    /// type's default. A feature declares its configuration type with this
151    /// binding
152    /// ([`SettingsDecl::config`](crate::core::settings::SettingsDecl::config)),
153    /// so that the configuration appears in the registry's list of option
154    /// declarations
155    /// ([`FlmRegistry::options`](crate::core::registry::FlmRegistry::options))
156    /// and in the settings schema.
157    Registry,
158    /// Set on the document ([`Doc::with_options`](crate::model::doc::Doc::with_options)).
159    Document,
160    /// Set on the render request
161    /// ([`PlanRequest::render_options`](crate::core::plan::PlanRequest::render_options())).
162    Render,
163    /// Set on the document, on the render request, or on both; a value set on
164    /// the render request replaces the document's value for the runs of that
165    /// plan.
166    Either,
167}
168
169/// One of the two places where a caller sets option values: the document or
170/// the render request.
171///
172/// A [`Bind`] admits some of these places and refuses the others
173/// ([`Bind::admits`]). The errors of [`validate_values`] hold the place, so
174/// that a report says where the value in question was set. Its `Display` form
175/// is `document` or `render request`.
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
177pub enum BindSite {
178    /// The document, through
179    /// [`Doc::with_options`](crate::model::doc::Doc::with_options).
180    Document,
181    /// The render request, through
182    /// [`PlanRequest::render_options`](crate::core::plan::PlanRequest::render_options()).
183    Render,
184}
185
186impl Bind {
187    /// Returns `true` when this binding lets a value be set in the place
188    /// `site`.
189    ///
190    /// [`Bind::Registry`] admits neither place; [`Bind::Either`] admits both.
191    ///
192    /// # Examples
193    ///
194    /// ```
195    /// use flm_core::model::options::{Bind, BindSite};
196    ///
197    /// assert!(Bind::Either.admits(BindSite::Document));
198    /// assert!(Bind::Either.admits(BindSite::Render));
199    /// assert!(!Bind::Render.admits(BindSite::Document));
200    /// assert!(!Bind::Registry.admits(BindSite::Render));
201    /// ```
202    pub fn admits(self, site: BindSite) -> bool {
203        matches!(
204            (self, site),
205            (Bind::Either, _)
206                | (Bind::Document, BindSite::Document)
207                | (Bind::Render, BindSite::Render)
208        )
209    }
210
211    /// The binding's name: `registry`, `document`, `render` or `either`. It is
212    /// the `Display` form, the value written in a settings schema, and part of
213    /// the registry digest.
214    pub fn label(self) -> &'static str {
215        match self {
216            Bind::Registry => "registry",
217            Bind::Document => "document",
218            Bind::Render => "render",
219            Bind::Either => "either",
220        }
221    }
222}
223
224impl fmt::Display for Bind {
225    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226        f.write_str(self.label())
227    }
228}
229
230impl fmt::Display for BindSite {
231    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232        f.write_str(match self {
233            BindSite::Document => "document",
234            BindSite::Render => "render request",
235        })
236    }
237}
238
239/// The requirements an option type meets: a value that can be shared between
240/// threads (`Any + Send + Sync`), has a default (`Default`), can be digested
241/// (`Hash`) and can be printed in messages (`Debug`).
242///
243/// This trait has no methods and is implemented for every type that meets the
244/// requirements, so a feature writes a plain struct and derives `Default`,
245/// `Hash` and `Debug` on it.
246pub trait Options: Any + Send + Sync + Default + Hash + fmt::Debug {}
247
248impl<T: Any + Send + Sync + Default + Hash + fmt::Debug> Options for T {}
249
250/// A Rust type name without its module path, as messages show it.
251///
252/// `"flm_core::stdlib::features::refs::tables::Labels"` becomes `"Labels"`.
253/// The generic arguments are kept as written, with their paths, since the
254/// outer name is enough to identify the type in a message.
255///
256/// # Examples
257///
258/// ```
259/// use flm_core::model::options::short_type_name;
260///
261/// assert_eq!(short_type_name("std::vec::Vec<my::crate::Thing>"), "Vec<my::crate::Thing>");
262/// assert_eq!(short_type_name("Labels"), "Labels");
263/// ```
264pub fn short_type_name(name: &'static str) -> &'static str {
265    // The module path of the outer type is dropped; a generic argument keeps
266    // its own spelling (the outer name is enough to name the type in a message).
267    let head_end = name.find('<').unwrap_or(name.len());
268    match name[..head_end].rfind("::") {
269        Some(pos) => &name[pos + 2..],
270        None => name,
271    }
272}
273
274/// The identifier of a Rust type, usable as a map key: the type's name and its
275/// `TypeId`.
276///
277/// Keys compare and order by the type's name first, so a collection keyed by
278/// them is visited in the same order in every build and every process, and
279/// the messages and digests computed from it are the same each time. The
280/// `TypeId` is what a downcast is checked against.
281///
282/// [`OptionKey::Type`] holds one for an option type that is a Rust type.
283#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
284pub struct TypeKey {
285    type_name: &'static str,
286    type_id: TypeId,
287}
288
289impl TypeKey {
290    /// The key of the type `T`.
291    pub fn of<T: ?Sized + Any>() -> TypeKey {
292        TypeKey { type_name: std::any::type_name::<T>(), type_id: TypeId::of::<T>() }
293    }
294
295    /// The type's full Rust name, path included.
296    pub fn type_name(&self) -> &'static str {
297        self.type_name
298    }
299
300    /// The type's name without its module path, as messages show it
301    /// ([`short_type_name`]).
302    pub fn short_name(&self) -> &'static str {
303        short_type_name(self.type_name)
304    }
305
306    /// The type's `TypeId`, against which a downcast is checked.
307    pub fn type_id(&self) -> TypeId {
308        self.type_id
309    }
310
311    /// Returns `true` when this is the key of the type `T`.
312    pub fn is<T: ?Sized + Any>(&self) -> bool {
313        self.type_id == TypeId::of::<T>()
314    }
315}
316
317impl fmt::Debug for TypeKey {
318    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
319        write!(f, "TypeKey({})", self.short_name())
320    }
321}
322
323impl fmt::Display for TypeKey {
324    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
325        f.write_str(self.short_name())
326    }
327}
328
329/// The identifier of an option type: a Rust type, or a name given as data.
330///
331/// An option type declared with a Rust type has no name of its own: a feature
332/// declares it once, and every other piece of code refers to it by its Rust
333/// type ([`OptionKey::of`]). An option type declared from data
334/// ([`SettingsDecl::options_data`](crate::core::settings::SettingsDecl::options_data),
335/// [`SettingsDecl::config_data`](crate::core::settings::SettingsDecl::config_data))
336/// is referred to by its name ([`OptionKey::named`]), and its values are
337/// [`DataValue`]s. A type key and a data key never compare equal.
338///
339/// Keys order the type keys first, by the type's name, then the data keys, by
340/// their name, so a collection keyed by them is visited in the same order in
341/// every build and every process. The `Debug` form is `OptionKey(NAME)` and the
342/// `Display` form is [`short_name`](OptionKey::short_name).
343#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
344pub enum OptionKey {
345    /// An option type that is a Rust type.
346    Type(TypeKey),
347    /// An option type declared from data, named by the feature's name (a
348    /// configuration) or by a name the feature gives (an option type).
349    Data(Name),
350}
351
352impl OptionKey {
353    /// The key of the option type that is the Rust type `T`.
354    pub fn of<T: ?Sized + Any>() -> OptionKey {
355        OptionKey::Type(TypeKey::of::<T>())
356    }
357
358    /// The key of the option type declared from data under the name `name`.
359    pub fn named(name: impl Into<Name>) -> OptionKey {
360        OptionKey::Data(name.into())
361    }
362
363    /// The name messages show: the Rust type's name without its module path
364    /// ([`short_type_name`]), or the name of an option type declared from data.
365    pub fn short_name(&self) -> &str {
366        match self {
367            OptionKey::Type(key) => key.short_name(),
368            OptionKey::Data(name) => name.as_str(),
369        }
370    }
371
372    /// The Rust type's key, or `None` for an option type declared from data.
373    pub fn type_key(&self) -> Option<&TypeKey> {
374        match self {
375            OptionKey::Type(key) => Some(key),
376            OptionKey::Data(_) => None,
377        }
378    }
379
380    /// Returns `true` when this is the key of the Rust type `T`; always `false`
381    /// for an option type declared from data.
382    pub fn is<T: ?Sized + Any>(&self) -> bool {
383        self.type_key().is_some_and(TypeKey::is::<T>)
384    }
385
386    /// Writes what identifies the key into a digest: the Rust type's full name,
387    /// or `data:` followed by the name. The digests of option values and the
388    /// registry digest use it.
389    pub(crate) fn write_digest(&self, hasher: &mut Fnv1a64) {
390        match self {
391            OptionKey::Type(key) => hasher.write_str(key.type_name()),
392            OptionKey::Data(name) => {
393                hasher.write_str("data:");
394                hasher.write_str(name.as_str());
395            }
396        }
397    }
398}
399
400impl fmt::Debug for OptionKey {
401    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402        write!(f, "OptionKey({})", self.short_name())
403    }
404}
405
406impl fmt::Display for OptionKey {
407    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
408        f.write_str(self.short_name())
409    }
410}
411
412/// The value of a configuration or of an option type declared from data: the
413/// data as written. Its default is the empty map.
414///
415/// It implements [`Options`]: every option type declared from data stores its
416/// values as a `DataValue`, under its own [`OptionKey::Data`]. Two values equal
417/// as data hash equal, whatever the order their maps' entries were written in
418/// ([`hash_value`]).
419#[derive(Debug, Clone, PartialEq)]
420pub struct DataValue(pub Value);
421
422impl Default for DataValue {
423    fn default() -> DataValue {
424        DataValue(Value::Object(Map::new()))
425    }
426}
427
428impl Hash for DataValue {
429    fn hash<H: Hasher>(&self, state: &mut H) {
430        hash_value(&self.0, state);
431    }
432}
433
434/// Hashes `value` with every map's entries in the order of their keys, so that
435/// two values equal as data hash equal in any order written.
436///
437/// A number is hashed through its text, so `1` and `1.0` hash apart, as they
438/// compare apart; `-0.0` is hashed as `0.0`, to which it compares equal.
439pub fn hash_value<H: Hasher>(value: &Value, state: &mut H) {
440    match value {
441        Value::Null => 0u8.hash(state),
442        Value::Bool(flag) => (1u8, flag).hash(state),
443        Value::Number(number) if number.is_f64() && number.as_f64() == Some(0.0) => (2u8, "0.0").hash(state),
444        Value::Number(number) => (2u8, number.to_string()).hash(state),
445        Value::String(text) => (3u8, text).hash(state),
446        Value::Array(items) => {
447            (4u8, items.len()).hash(state);
448            for item in items {
449                hash_value(item, state);
450            }
451        }
452        Value::Object(map) => {
453            5u8.hash(state);
454            let mut entries: Vec<(&String, &Value)> = map.iter().collect();
455            entries.sort_by(|a, b| a.0.cmp(b.0));
456            entries.len().hash(state);
457            for (key, value) in entries {
458                key.hash(state);
459                hash_value(value, state);
460            }
461        }
462    }
463}
464
465type ErasedValue = Arc<dyn Any + Send + Sync>;
466
467fn default_erased<T: Options>() -> ErasedValue {
468    Arc::new(T::default())
469}
470
471fn digest_erased<T: Options>(value: &(dyn Any + Send + Sync)) -> u64 {
472    digest_of(value.downcast_ref::<T>().expect("an option value is digested through its own type"))
473}
474
475/// A stage's declaration that it reads one option type: the option type,
476/// with the two operations on it that resolving the read needs and cannot
477/// perform on a value whose type is erased (creating the type's default, and
478/// digesting a value).
479///
480/// [`Needs::option`](crate::core::stage::Needs::option) and
481/// [`LoweringDecl::option`](crate::core::lowering::LoweringDecl::option)
482/// create one per option type a stage or a lowering rule reads. Reads compare
483/// and order by their [key](OptionRef::key), so declaring the same read twice
484/// declares it once. [`OptionRef::named`] declares a read of an option type
485/// declared from data.
486#[derive(Clone)]
487pub struct OptionRef {
488    key: OptionKey,
489    make_default: fn() -> ErasedValue,
490    digest: fn(&(dyn Any + Send + Sync)) -> u64,
491}
492
493impl OptionRef {
494    /// The declaration of a read of the option type `T`.
495    pub fn of<T: Options>() -> OptionRef {
496        OptionRef {
497            key: OptionKey::of::<T>(),
498            make_default: default_erased::<T>,
499            digest: digest_erased::<T>,
500        }
501    }
502
503    /// The declaration of a read of the option type declared from data under
504    /// the name `name`; the read resolves to a [`DataValue`], the empty map
505    /// when no value is set.
506    pub fn named(name: impl Into<Name>) -> OptionRef {
507        OptionRef {
508            key: OptionKey::named(name),
509            make_default: default_erased::<DataValue>,
510            digest: digest_erased::<DataValue>,
511        }
512    }
513
514    /// The option type read.
515    pub fn key(&self) -> &OptionKey {
516        &self.key
517    }
518
519    /// A new default value of the option type, with its type erased: what a
520    /// read resolves to when no value is set on the render request or on the
521    /// document.
522    pub fn make_default(&self) -> ErasedValue {
523        (self.make_default)()
524    }
525
526    /// The digest of `value`: [`digest_of`] applied through the option type's
527    /// [`Hash`] implementation. The same value gives the same number in every
528    /// process.
529    ///
530    /// # Panics
531    ///
532    /// Panics if `value` is not a value of this read's option type. The
533    /// library always passes a value of the matching type, so no document can
534    /// cause this panic.
535    pub fn digest(&self, value: &(dyn Any + Send + Sync)) -> u64 {
536        (self.digest)(value)
537    }
538}
539
540impl PartialEq for OptionRef {
541    fn eq(&self, other: &OptionRef) -> bool {
542        self.key == other.key
543    }
544}
545
546impl Eq for OptionRef {}
547
548impl PartialOrd for OptionRef {
549    fn partial_cmp(&self, other: &OptionRef) -> Option<std::cmp::Ordering> {
550        Some(self.cmp(other))
551    }
552}
553
554impl Ord for OptionRef {
555    fn cmp(&self, other: &OptionRef) -> std::cmp::Ordering {
556        self.key.cmp(&other.key)
557    }
558}
559
560/// Writes an option reference to data as the name of the option type it
561/// refers to ([`OptionKey::short_name`]); see [serialized
562/// forms](crate::core::registry#serialized-forms).
563impl serde::Serialize for OptionRef {
564    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
565        serializer.serialize_str(self.key.short_name())
566    }
567}
568
569/// Describes an option reference in a JSON schema as a string, the form
570/// `Serialize` writes.
571impl schemars::JsonSchema for OptionRef {
572    fn schema_name() -> std::borrow::Cow<'static, str> {
573        "String".into()
574    }
575
576    fn inline_schema() -> bool {
577        true
578    }
579
580    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
581        String::json_schema(generator)
582    }
583}
584
585/// Writes an option key to data as its name ([`OptionKey::short_name`]), for
586/// [`OptionDecl`]'s serialized form.
587fn serialize_key_name<S: serde::Serializer>(key: &OptionKey, serializer: S) -> Result<S::Ok, S::Error> {
588    serializer.serialize_str(key.short_name())
589}
590
591impl fmt::Debug for OptionRef {
592    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
593        write!(f, "OptionRef({})", self.key.short_name())
594    }
595}
596
597/// A feature's declaration of one option type: the type, its binding, the
598/// feature that declares it, and its description.
599///
600/// [`FeatureBuilder::options`](crate::core::registry::FeatureBuilder::options)
601/// creates one; the registry collects them from every feature
602/// ([`FlmRegistry::options`](crate::core::registry::FlmRegistry::options)), and
603/// the option values a caller sets are checked against them
604/// ([`validate_values`]).
605///
606/// It is written to data with `Serialize`; see [serialized
607/// forms](crate::core::registry#serialized-forms).
608#[derive(Debug, Clone)]
609#[derive(serde::Serialize, schemars::JsonSchema)]
610pub struct OptionDecl {
611    /// The option type declared.
612    #[serde(serialize_with = "serialize_key_name")]
613    #[schemars(with = "String")]
614    pub key: OptionKey,
615    /// The binding: where values for the option type may be set.
616    pub bind: Bind,
617    /// The feature that declares the option type and owns it.
618    pub owner: FeatureName,
619    /// A description of what the option type sets, for a person who reads the
620    /// registry's declarations
621    /// ([`FlmRegistry::options`](crate::core::registry::FlmRegistry::options));
622    /// empty unless the feature gave one
623    /// ([`FeatureBuilder::options_with_docs`](crate::core::registry::FeatureBuilder::options_with_docs)).
624    pub docs: String,
625}
626
627impl OptionDecl {
628    /// The declaration of the option type `T` by the feature `owner`, with the
629    /// binding `bind` and an empty description.
630    pub fn of<T: Options>(owner: impl Into<FeatureName>, bind: Bind) -> OptionDecl {
631        OptionDecl { key: OptionKey::of::<T>(), bind, owner: owner.into(), docs: String::new() }
632    }
633
634    /// The declaration of the option type declared from data under the name
635    /// `name`, by the feature `owner`, with the binding `bind` and an empty
636    /// description.
637    pub fn named(name: impl Into<Name>, owner: impl Into<FeatureName>, bind: Bind) -> OptionDecl {
638        OptionDecl { key: OptionKey::named(name), bind, owner: owner.into(), docs: String::new() }
639    }
640
641    /// Builder: sets the description of the option type.
642    pub fn docs(mut self, docs: impl Into<String>) -> OptionDecl {
643        self.docs = crate::kept_docs(docs);
644        self
645    }
646}
647
648/// One option value set in one place, with its digest.
649#[derive(Clone)]
650struct OptionValue {
651    value: ErasedValue,
652    digest: u64,
653}
654
655/// The option values set in one place: at most one value per option type.
656///
657/// A caller fills one in to set option values on a document
658/// ([`Doc::with_options`](crate::model::doc::Doc::with_options)) or on a
659/// render request
660/// ([`PlanRequest::render_options`](crate::core::plan::PlanRequest::render_options())).
661/// Values are stored under the Rust type of the option struct, so setting a
662/// value needs no name and cannot be misspelled. Whether an option type may be
663/// set in that place is checked later, by [`validate_values`], when a run is
664/// constructed or a plan is built.
665///
666/// # Examples
667///
668/// ```
669/// use flm_core::model::options::OptionValues;
670///
671/// #[derive(Debug, Default, Hash, PartialEq, Eq)]
672/// struct Width(u32);
673///
674/// let values = OptionValues::new().with(Width(72));
675/// assert_eq!(values.get::<Width>(), Some(&Width(72)));
676/// assert_eq!(values.len(), 1);
677/// ```
678#[derive(Clone, Default)]
679pub struct OptionValues {
680    entries: BTreeMap<OptionKey, OptionValue>,
681}
682
683impl OptionValues {
684    /// A collection with no value set.
685    pub fn new() -> OptionValues {
686        OptionValues::default()
687    }
688
689    /// Sets `value` as the value of the option type `T`, replacing any value
690    /// set for `T` before.
691    pub fn set<T: Options>(&mut self, value: T) {
692        let digest = digest_of(&value);
693        self.entries.insert(OptionKey::of::<T>(), OptionValue { value: Arc::new(value), digest });
694    }
695
696    /// Builder: sets `value` as the value of the option type `T`, as
697    /// [`OptionValues::set`] does.
698    pub fn with<T: Options>(mut self, value: T) -> OptionValues {
699        self.set(value);
700        self
701    }
702
703    /// The value set for the option type `T` in this collection, or `None`
704    /// when none is set.
705    ///
706    /// This reads what was set in this one place. A stage may read another
707    /// value: it reads through [`ResolvedOptions`], which may give the value
708    /// set in the other place or the type's default.
709    pub fn get<T: Options>(&self) -> Option<&T> {
710        self.entries.get(&OptionKey::of::<T>()).and_then(|entry| entry.value.downcast_ref::<T>())
711    }
712
713    /// Sets `value` as the value of the option type declared from data under
714    /// the name `name`, replacing any value set for it before. The value is
715    /// stored as a [`DataValue`].
716    pub fn set_named(&mut self, name: impl Into<Name>, value: Value) {
717        let value = DataValue(value);
718        let digest = digest_of(&value);
719        self.entries.insert(OptionKey::named(name), OptionValue { value: Arc::new(value), digest });
720    }
721
722    /// The value set for the option type declared from data under the name
723    /// `name` in this collection, or `None` when none is set. As for
724    /// [`get`](OptionValues::get), a stage reads through [`ResolvedOptions`]
725    /// instead.
726    pub fn get_named(&self, name: &str) -> Option<&Value> {
727        self.entries
728            .get(&OptionKey::named(name))
729            .and_then(|entry| entry.value.downcast_ref::<DataValue>())
730            .map(|value| &value.0)
731    }
732
733    /// The value set for the option type `key`, with its type erased, or
734    /// `None` when none is set. For a caller that holds a key rather than the
735    /// Rust type.
736    pub fn get_erased(&self, key: &OptionKey) -> Option<&ErasedValue> {
737        self.entries.get(key).map(|entry| &entry.value)
738    }
739
740    /// Copies every value of `other` into this collection, replacing the value
741    /// of each option type that `other` sets and leaving the others unchanged.
742    ///
743    /// Each value is replaced whole: it is never combined field by field with
744    /// the value it replaces. Use this to let a caller's own values replace,
745    /// option type by option type, a set of values supplied together.
746    pub fn merge_from(&mut self, other: &OptionValues) {
747        for (key, entry) in &other.entries {
748            self.entries.insert(key.clone(), entry.clone());
749        }
750    }
751
752    /// The option types that have a value set, in key order.
753    pub fn keys(&self) -> impl Iterator<Item = OptionKey> + '_ {
754        self.entries.keys().cloned()
755    }
756
757    /// The number of option types that have a value set.
758    pub fn len(&self) -> usize {
759        self.entries.len()
760    }
761
762    /// Returns `true` when no value is set.
763    pub fn is_empty(&self) -> bool {
764        self.entries.is_empty()
765    }
766
767    /// The digest of the whole collection: the option types and their values,
768    /// in key order.
769    ///
770    /// Two collections that set the same values give the same number, in every
771    /// process and every build. The digest of a plan request's render option
772    /// values is part of the plan's identity
773    /// ([`PlanKey`](crate::core::plan::PlanKey)), so plans built with different
774    /// render option values are different plans.
775    pub fn digest(&self) -> u64 {
776        let mut hasher = Fnv1a64::new();
777        for (key, entry) in &self.entries {
778            key.write_digest(&mut hasher);
779            hasher.write_u64(entry.digest);
780        }
781        hasher.value()
782    }
783}
784
785impl fmt::Debug for OptionValues {
786    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
787        f.debug_list().entries(self.entries.keys()).finish()
788    }
789}
790
791/// An error about option types and option values.
792///
793/// Each variant holds what a report needs, including the option types that
794/// were available, so that a message can list them without looking anything
795/// up again. A plan build returns these inside
796/// [`PlanError`](crate::core::plan::PlanError), a run inside
797/// [`RunError::DocumentOption`](crate::core::run::RunError::DocumentOption),
798/// and a stage's read of an option directly.
799#[derive(Debug, Clone, PartialEq, Eq)]
800pub enum OptionError {
801    /// A stage read an option type that it did not declare. The read returns
802    /// this error rather than the type's default, so that a missing
803    /// declaration is reported instead of changing what the stage computes.
804    UndeclaredRead {
805        /// The stage, rewrite stage or lowering rule that read the option type.
806        stage: StageName,
807        /// The option type it read, by short name ([`OptionKey::short_name`]).
808        option: String,
809        /// The option types it declared, by short name.
810        declared: Vec<String>,
811    },
812    /// A value was set for an option type that no feature of the registry
813    /// declares.
814    UnknownOption {
815        /// Where the value was set.
816        site: BindSite,
817        /// The option type, by short name.
818        option: String,
819        /// Every option type the registry declares, by short name.
820        roster: Vec<String>,
821        /// The workflow whose render request sets the value, or `None` for a
822        /// value set on the document or on a render request built by hand.
823        workflow: Option<WorkflowName>,
824    },
825    /// A value was set in a place that the option type's binding does not
826    /// admit, for example on the document for an option type bound to the
827    /// render request.
828    BindingRefused {
829        /// Where the value was set.
830        site: BindSite,
831        /// The option type, by short name.
832        option: String,
833        /// The binding that the feature declared.
834        declared: Bind,
835        /// The feature that declares the option type.
836        owner: FeatureName,
837        /// The workflow whose render request sets the value, or `None` for a
838        /// value set on the document or on a render request built by hand.
839        workflow: Option<WorkflowName>,
840    },
841    /// A stage declared a read of an option type whose binding is
842    /// [`Bind::Registry`]. Such a read could only return the type's default,
843    /// since no value can be set for it; the feature that declares the option
844    /// type holds the value in its configuration.
845    RegistryBoundRead {
846        /// The stage that declared the read.
847        stage: StageName,
848        /// The option type, by short name.
849        option: String,
850        /// The feature that declares the option type.
851        owner: FeatureName,
852    },
853}
854
855impl fmt::Display for OptionError {
856    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
857        match self {
858            OptionError::UndeclaredRead { stage, option, declared } => write!(
859                f,
860                "stage `{stage}` must declare each option type it reads, but it reads \
861                 `{option}` without declaring it; it declares: [{}]",
862                declared.join(", ")
863            ),
864            OptionError::UnknownOption { site, option, roster, workflow } => write!(
865                f,
866                "{} for the option type `{option}`, but no feature declares that option type; \
867                 declared option types: [{}]",
868                value_set(*site, workflow),
869                roster.join(", ")
870            ),
871            OptionError::BindingRefused { site, option, declared, owner, workflow } => write!(
872                f,
873                "{} for the option type `{option}` of feature `{owner}`, but feature `{owner}` \
874                 declares that values of this option type may be set only {}",
875                value_set(*site, workflow),
876                match declared {
877                    Bind::Registry => {
878                        format!("in the configuration of feature `{owner}`, when the registry is built")
879                    }
880                    Bind::Document => "on the document".to_string(),
881                    Bind::Render => "on the render request".to_string(),
882                    Bind::Either => "on the document or on the render request".to_string(),
883                }
884            ),
885            OptionError::RegistryBoundRead { stage, option, owner } => write!(
886                f,
887                "stage `{stage}` declares a read of the option type `{option}` of feature \
888                 `{owner}`, but feature `{owner}` fixes the value of that option type when the \
889                 registry is built, so no stage can read it"
890            ),
891        }
892    }
893}
894
895impl std::error::Error for OptionError {}
896
897/// The opening of a message about a value set for an option type: "a value is
898/// set on the render request of workflow `w`" when the value is set on the
899/// render request of the workflow `w`, and "a value is set on the document"
900/// (or "on the render request") otherwise. The render request of a workflow
901/// holds the workflow's values and the caller's, so the sentence names the
902/// request, not the workflow, as the one that sets the value.
903fn value_set(site: BindSite, workflow: &Option<WorkflowName>) -> String {
904    match workflow {
905        Some(workflow) => format!("a value is set on the {site} of workflow `{workflow}`"),
906        None => format!("a value is set on the {site}"),
907    }
908}
909
910/// Checks the option values `values`, set in the place `site`, against the
911/// option declarations: each value's option type must be declared, with a
912/// binding that admits `site`.
913///
914/// `lookup` returns the declaration of an option type, or `None` when no
915/// feature declares it; `roster` lists every declared option type, which the
916/// error lists when a value is set for an undeclared type. `workflow` is the
917/// workflow whose render request sets the values, which the errors name; it is
918/// `None` for the document's values and for a render request built by hand
919/// ([`PlanRequest::workflow`](crate::core::plan::PlanRequest::workflow)). Returns every
920/// error found, in key order: an [`OptionError::UnknownOption`] or an
921/// [`OptionError::BindingRefused`] per value in question, and an empty list
922/// when every value is admitted.
923///
924/// The library calls this when a run is constructed
925/// ([`Run::new`](crate::core::run::Run::new)), for the values set on the
926/// document, and when a plan is built, for the values set on the render
927/// request; both report the first error only. The registry build calls it for
928/// the render option values of every workflow and reports every error.
929pub fn validate_values<'d>(
930    values: &OptionValues,
931    site: BindSite,
932    lookup: impl Fn(&OptionKey) -> Option<&'d OptionDecl>,
933    roster: &[OptionKey],
934    workflow: Option<&WorkflowName>,
935) -> Vec<OptionError> {
936    let mut errors = Vec::new();
937    for key in values.keys() {
938        match lookup(&key) {
939            None => errors.push(OptionError::UnknownOption {
940                site,
941                option: key.short_name().to_string(),
942                roster: roster.iter().map(|key| key.short_name().to_string()).collect(),
943                workflow: workflow.cloned(),
944            }),
945            Some(decl) if !decl.bind.admits(site) => errors.push(OptionError::BindingRefused {
946                site,
947                option: key.short_name().to_string(),
948                declared: decl.bind,
949                owner: decl.owner.clone(),
950                workflow: workflow.cloned(),
951            }),
952            Some(_) => {}
953        }
954    }
955    errors
956}
957
958/// One stage's declared option reads, resolved to values.
959///
960/// A run builds one per scheduled stage when it is constructed, so that every
961/// read within the stage returns the same value, and the stage reads the
962/// values through its context
963/// ([`StageCx::option`](crate::core::run::StageCx::option)). A read of an
964/// option type that the stage did not declare returns an error
965/// ([`OptionError::UndeclaredRead`]), not the type's default.
966#[derive(Clone)]
967pub struct ResolvedOptions {
968    stage: StageName,
969    entries: BTreeMap<OptionKey, (ErasedValue, u64)>,
970}
971
972impl ResolvedOptions {
973    /// Resolves each read in `reads`, the declared reads of the stage
974    /// `stage`: to the value set in `render` if there is one, otherwise the
975    /// value set in `document` if there is one, otherwise the option type's
976    /// default.
977    ///
978    /// This function checks nothing. Check both collections with
979    /// [`validate_values`] first, so that every value found here is admitted
980    /// by its binding.
981    pub fn resolve(
982        stage: StageName,
983        reads: &[OptionRef],
984        render: &OptionValues,
985        document: &OptionValues,
986    ) -> ResolvedOptions {
987        let mut entries = BTreeMap::new();
988        for read in reads {
989            let key = read.key().clone();
990            let (value, digest) =
991                match render.entries.get(&key).or_else(|| document.entries.get(&key)) {
992                    Some(entry) => (Arc::clone(&entry.value), entry.digest),
993                    None => {
994                        let value = read.make_default();
995                        let digest = read.digest(value.as_ref());
996                        (value, digest)
997                    }
998                };
999            entries.insert(key, (value, digest));
1000        }
1001        ResolvedOptions { stage, entries }
1002    }
1003
1004    /// The resolved value of the option type `T`.
1005    ///
1006    /// # Errors
1007    ///
1008    /// Returns [`OptionError::UndeclaredRead`], with the stage and the option
1009    /// types it declared, when `T` is not among the stage's declared reads.
1010    pub fn get<T: Options>(&self) -> Result<&T, OptionError> {
1011        let key = OptionKey::of::<T>();
1012        match self.entries.get(&key) {
1013            Some((value, _)) => Ok(value
1014                .downcast_ref::<T>()
1015                .expect("a resolved option is stored under its own type")),
1016            None => Err(self.undeclared(key.short_name())),
1017        }
1018    }
1019
1020    /// The resolved value of the option type declared from data under the name
1021    /// `name`: the data as written, or the empty map when no value is set.
1022    ///
1023    /// # Errors
1024    ///
1025    /// Returns [`OptionError::UndeclaredRead`], with the stage, the name and the
1026    /// option types it declared, when the stage did not declare a read of
1027    /// `name` ([`OptionRef::named`]).
1028    pub fn get_named(&self, name: &str) -> Result<&Value, OptionError> {
1029        match self.entries.get(&OptionKey::named(name)) {
1030            Some((value, _)) => Ok(&value
1031                .downcast_ref::<DataValue>()
1032                .expect("an option declared from data is stored as a `DataValue`")
1033                .0),
1034            None => Err(self.undeclared(name)),
1035        }
1036    }
1037
1038    /// The error of a read of `option`, which the stage did not declare.
1039    fn undeclared(&self, option: &str) -> OptionError {
1040        OptionError::UndeclaredRead {
1041            stage: self.stage.clone(),
1042            option: option.to_string(),
1043            declared: self.entries.keys().map(|key| key.short_name().to_string()).collect(),
1044        }
1045    }
1046
1047    /// The option types the stage declared, in key order.
1048    pub fn keys(&self) -> impl Iterator<Item = OptionKey> + '_ {
1049        self.entries.keys().cloned()
1050    }
1051
1052    /// The resolved value of the option type `key`, with its type erased, or
1053    /// `None` when the stage did not declare that read.
1054    ///
1055    /// For a caller that holds a key rather than the Rust type: the lowering
1056    /// driver returns a lowering rule's option reads through it
1057    /// ([`Lowerer::option_erased`](crate::core::lowering::Lowerer::option_erased)),
1058    /// after checking the read against the rule's own declaration.
1059    pub fn get_erased(&self, key: &OptionKey) -> Option<&(dyn Any + Send + Sync)> {
1060        self.entries.get(key).map(|(value, _)| &**value)
1061    }
1062
1063    /// The digest of the resolved values: the option types and their values,
1064    /// in key order.
1065    ///
1066    /// It is the same in every process for the same values. The stamp of an
1067    /// external table ([`Stamp`](crate::core::run::Stamp)) includes the digests
1068    /// of the values that the rewrite stages read, so that data computed with
1069    /// other option values is not mistaken for data computed with these.
1070    pub fn digest(&self) -> u64 {
1071        let mut hasher = Fnv1a64::new();
1072        for (key, (_, digest)) in &self.entries {
1073            key.write_digest(&mut hasher);
1074            hasher.write_u64(*digest);
1075        }
1076        hasher.value()
1077    }
1078}
1079
1080impl fmt::Debug for ResolvedOptions {
1081    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1082        f.debug_struct("ResolvedOptions")
1083            .field("stage", &self.stage)
1084            .field("options", &self.entries.keys().collect::<Vec<_>>())
1085            .finish()
1086    }
1087}
1088
1089#[cfg(test)]
1090mod tests {
1091    use super::*;
1092
1093    #[derive(Debug, Default, Hash, PartialEq, Eq)]
1094    struct Width(u32);
1095
1096    #[derive(Debug, Default, Hash)]
1097    struct Depth(u32);
1098
1099    #[test]
1100    fn a_binding_admits_its_own_site_and_either_admits_both() {
1101        assert!(Bind::Document.admits(BindSite::Document));
1102        assert!(!Bind::Document.admits(BindSite::Render));
1103        assert!(Bind::Render.admits(BindSite::Render));
1104        assert!(!Bind::Render.admits(BindSite::Document));
1105        assert!(Bind::Either.admits(BindSite::Document));
1106        assert!(Bind::Either.admits(BindSite::Render));
1107        assert!(!Bind::Registry.admits(BindSite::Document));
1108    }
1109
1110    #[test]
1111    fn resolution_takes_render_over_document_over_default() {
1112        let reads = [OptionRef::of::<Width>(), OptionRef::of::<Depth>()];
1113        let render = OptionValues::new().with(Width(120));
1114        let document = OptionValues::new().with(Width(100)).with(Depth(5));
1115        let resolved = ResolvedOptions::resolve("s".into(), &reads, &render, &document);
1116        assert_eq!(resolved.get::<Width>().unwrap(), &Width(120));
1117        assert_eq!(resolved.get::<Depth>().unwrap().0, 5);
1118        let none = ResolvedOptions::resolve(
1119            "s".into(),
1120            &reads,
1121            &OptionValues::new(),
1122            &OptionValues::new(),
1123        );
1124        assert_eq!(none.get::<Width>().unwrap(), &Width(0));
1125    }
1126
1127    #[test]
1128    fn an_undeclared_read_is_a_typed_error() {
1129        let resolved =
1130            ResolvedOptions::resolve("s".into(), &[], &OptionValues::new(), &OptionValues::new());
1131        let error = resolved.get::<Width>().unwrap_err();
1132        assert!(matches!(error, OptionError::UndeclaredRead { ref option, .. } if option == "Width"));
1133    }
1134
1135    #[test]
1136    fn values_at_a_refused_site_are_reported() {
1137        let decl = OptionDecl::of::<Width>("f", Bind::Render);
1138        let values = OptionValues::new().with(Width(1)).with(Depth(2));
1139        let errors = validate_values(
1140            &values,
1141            BindSite::Document,
1142            |key| if key.is::<Width>() { Some(&decl) } else { None },
1143            &[OptionKey::of::<Width>()],
1144            None,
1145        );
1146        assert_eq!(errors.len(), 2);
1147        assert!(matches!(errors[0], OptionError::UnknownOption { ref option, .. } if option == "Depth"));
1148        assert!(matches!(errors[1], OptionError::BindingRefused { ref option, .. } if option == "Width"));
1149    }
1150
1151    #[test]
1152    fn the_values_digest_depends_on_the_values() {
1153        let a = OptionValues::new().with(Width(1));
1154        let b = OptionValues::new().with(Width(2));
1155        assert_ne!(a.digest(), b.digest());
1156        assert_eq!(a.digest(), OptionValues::new().with(Width(1)).digest());
1157    }
1158
1159    fn hash_of(value: &DataValue) -> u64 {
1160        let mut hasher = std::collections::hash_map::DefaultHasher::new();
1161        value.hash(&mut hasher);
1162        hasher.finish()
1163    }
1164
1165    #[test]
1166    fn equal_data_values_hash_equal_whatever_the_order_of_their_entries() {
1167        let one = DataValue(serde_json::json!({ "a": 1, "b": { "x": [1, 2], "y": "t" } }));
1168        let two = DataValue(serde_json::json!({ "b": { "y": "t", "x": [1, 2] }, "a": 1 }));
1169        assert_eq!(one, two);
1170        assert_eq!(hash_of(&one), hash_of(&two));
1171        assert_eq!(digest_of(&one), digest_of(&two));
1172        let other = DataValue(serde_json::json!({ "a": 2, "b": { "x": [1, 2], "y": "t" } }));
1173        assert_ne!(hash_of(&one), hash_of(&other));
1174        assert_eq!(DataValue::default(), DataValue(serde_json::json!({})));
1175        let (negative, zero) = (DataValue(serde_json::json!(-0.0)), DataValue(serde_json::json!(0.0)));
1176        assert_eq!(negative, zero);
1177        assert_eq!(hash_of(&negative), hash_of(&zero));
1178    }
1179
1180    #[test]
1181    fn a_type_key_and_a_data_key_never_compare_equal() {
1182        // A data option named as a Rust type's full name is still another key.
1183        let full = std::any::type_name::<Width>();
1184        assert_ne!(OptionKey::of::<Width>(), OptionKey::named(full));
1185        assert_ne!(OptionKey::of::<Width>(), OptionKey::named("Width"));
1186        assert_eq!(OptionKey::named("w.display"), OptionKey::named("w.display"));
1187        assert!(OptionKey::of::<Width>() < OptionKey::named("a"));
1188        assert!(OptionKey::of::<Width>().is::<Width>());
1189        assert!(!OptionKey::named("Width").is::<Width>());
1190        assert_eq!(OptionKey::named("w.display").short_name(), "w.display");
1191        // Their values, set side by side, stay apart, and so do their digests.
1192        let values = OptionValues::new().with(Width(1));
1193        let mut named = values.clone();
1194        named.set_named("Width", serde_json::json!({ "w": 1 }));
1195        assert_eq!(named.len(), 2);
1196        assert_eq!(named.get::<Width>(), Some(&Width(1)));
1197        assert_eq!(named.get_named("Width"), Some(&serde_json::json!({ "w": 1 })));
1198        assert_ne!(values.digest(), named.digest());
1199    }
1200
1201    #[test]
1202    fn a_data_read_resolves_to_the_value_set_or_the_empty_map() {
1203        let reads = [OptionRef::named("w.display"), OptionRef::named("w.other")];
1204        let mut document = OptionValues::new();
1205        document.set_named("w.display", serde_json::json!({ "size": 3 }));
1206        let resolved = ResolvedOptions::resolve("s".into(), &reads, &OptionValues::new(), &document);
1207        assert_eq!(resolved.get_named("w.display").unwrap(), &serde_json::json!({ "size": 3 }));
1208        assert_eq!(resolved.get_named("w.other").unwrap(), &serde_json::json!({}));
1209        let error = resolved.get_named("w.none").unwrap_err();
1210        assert_eq!(
1211            error.to_string(),
1212            "stage `s` must declare each option type it reads, but it reads `w.none` without \
1213             declaring it; it declares: [w.display, w.other]"
1214        );
1215    }
1216}