fig_schema/consequence.rs
1//! What changing a field *costs* — declared beside the rule, surfaced by the
2//! host before it commits. The three properties a host has to know are on
3//! [`Consequence`] itself, since this module is private and its docs do not
4//! reach an embedder.
5
6use fig::Value;
7
8use crate::field::FieldRule;
9use crate::vocab::Term;
10
11/// What the host should *do* about a consequence — the interaction, not a
12/// measure of how bad it is. Mirrors [`Validation`](crate::Validation)'s
13/// Ok/Warn/Reject: the crate names the response, the embedder renders it.
14///
15/// Exhaustive on purpose, unlike most of this crate's enums. A host that met an
16/// unhandled severity through a `_` arm would quietly under-warn about the
17/// change it was told to warn about hardest, which is the exact failure this
18/// type exists to prevent. Adding a level is worth a major.
19///
20/// Ordering is severity order, ascending — see [`FieldRule::severity_of`].
21#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
22pub enum Severity {
23 /// Say so, but don't interrupt: an inline note beside the field.
24 Notice,
25 /// Ask before committing — an ordinary confirm/cancel.
26 Confirm,
27 /// Ask, and make agreeing deliberate: type the value, hold to confirm,
28 /// whatever the frontend's strongest gesture is. For a change that cannot
29 /// be undone.
30 ConfirmExplicitly,
31}
32
33impl Severity {
34 /// The severity a schema document's `severity` key names — `notice`,
35 /// `confirm`, `confirm_explicitly` — or `None` for any other spelling. The
36 /// loader treats that `None` as an error rather than a default, for the
37 /// reason this enum is exhaustive: under-warning about the change the
38 /// author warned about hardest is the one failure the type exists to
39 /// prevent.
40 ///
41 /// ```
42 /// use fig_schema::Severity;
43 ///
44 /// assert_eq!(Severity::from_name("confirm"), Some(Severity::Confirm));
45 /// assert_eq!(Severity::from_name("warn"), None);
46 /// ```
47 pub fn from_name(name: &str) -> Option<Severity> {
48 match name {
49 "notice" => Some(Severity::Notice),
50 "confirm" => Some(Severity::Confirm),
51 "confirm_explicitly" => Some(Severity::ConfirmExplicitly),
52 _ => None,
53 }
54 }
55
56 /// The name [`Severity::from_name`] reads this severity back from.
57 pub fn name(self) -> &'static str {
58 match self {
59 Severity::Notice => "notice",
60 Severity::Confirm => "confirm",
61 Severity::ConfirmExplicitly => "confirm_explicitly",
62 }
63 }
64}
65
66/// A cost of changing a field, declared on the rule that governs it.
67///
68/// A different fact from [`Presentation`](crate::Presentation)'s
69/// [`Tint`](crate::Tint). A tint says how loudly to draw a field; a consequence
70/// says what happens if the user goes through with the change — that switching
71/// a metadata format rewrites every document in the archive, that turning a
72/// recycle bin off makes deletion unrecoverable. A field can be drawn calmly
73/// and still be expensive to change, and a field can be drawn in red and cost
74/// nothing.
75///
76/// Three properties are deliberate, and a host that assumes otherwise will be
77/// subtly wrong:
78///
79/// - **A guard names the value being landed, not a transition.** There is no
80/// from/to matrix: [`Consequence::when`] names a destination. The host knows
81/// the current value; this crate does not. A cost that only applies coming
82/// *from* a particular value is declared as a plain consequence on the
83/// destination, and suppressed by the host that can see the difference.
84/// - **Deletion resolves to whatever the host's default is.** This crate has no
85/// concept of a field being absent, and [`Value::Null`] is not a spelling for
86/// it — a written null is a real value, which
87/// [`FieldType::Null`](crate::FieldType) coerces. A host removing a field
88/// should ask about the value the removal actually resolves to, or about
89/// nothing.
90/// - **No-op detection is the caller's.** [`FieldRule::consequences_of`] has no
91/// current value to compare against, so re-setting a field to what it already
92/// holds answers exactly as setting it afresh does. Suppressing that is the
93/// host's job — and it is what makes the first property work.
94///
95/// `#[non_exhaustive]`: built from [`Consequence::always`] or
96/// [`Consequence::when`] plus [`Consequence::severity`]. Reading the fields is
97/// unchanged.
98///
99/// ```
100/// use fig::Value;
101/// use fig_schema::{Consequence, Severity};
102///
103/// let c = Consequence::when(false, "Deleted items will be gone for good.")
104/// .severity(Severity::ConfirmExplicitly);
105/// assert_eq!(c.when, Some(Value::Bool(false)));
106/// ```
107#[derive(Debug, Clone, PartialEq)]
108#[non_exhaustive]
109pub struct Consequence {
110 /// The destination value this applies to, or `None` for *any* change to the
111 /// field. Compared with [`Value::eq_canonical`], so a guard written
112 /// `Value::Int(1)` still matches a document that parsed `1` as a
113 /// [`Value::Uint`].
114 pub when: Option<Value>,
115 /// What the host should do about it.
116 pub severity: Severity,
117 /// The sentence to show. Prose rather than a taxonomy: a consequence is
118 /// specific to the field, and no closed set of effect kinds would spare the
119 /// author from writing it.
120 pub message: String,
121}
122
123impl Consequence {
124 /// A consequence of changing the field at all, whatever the new value.
125 /// [`Severity::Notice`] until [`Consequence::severity`] says otherwise.
126 pub fn always(message: impl Into<String>) -> Self {
127 Self {
128 when: None,
129 severity: Severity::Notice,
130 message: message.into(),
131 }
132 }
133
134 /// A consequence of changing the field *to* `value` — a destination, not a
135 /// transition. See [`Consequence`] for why there is no from/to matrix.
136 pub fn when(value: impl Into<Value>, message: impl Into<String>) -> Self {
137 Self {
138 when: Some(value.into()),
139 severity: Severity::Notice,
140 message: message.into(),
141 }
142 }
143
144 /// Set what the host should do about this.
145 pub fn severity(mut self, severity: Severity) -> Self {
146 self.severity = severity;
147 self
148 }
149
150 /// Whether this applies to landing `value`. An unguarded consequence
151 /// applies to every value.
152 pub fn applies_to(&self, value: &Value) -> bool {
153 match &self.when {
154 None => true,
155 Some(guard) => guard.eq_canonical(value),
156 }
157 }
158}
159
160impl<C> FieldRule<C> {
161 /// Every consequence of landing `value` on this field, in declaration
162 /// order — the unguarded ones and the guards that match.
163 ///
164 /// All of them, not the worst: two consequences can be true at once (a
165 /// blanket "this rewrites the archive" and a value-specific "and `none`
166 /// cannot be undone"), and dropping either loses a sentence the user needed.
167 /// For picking one interaction, use [`FieldRule::severity_of`].
168 pub fn consequences_of(&self, value: &Value) -> Vec<&Consequence> {
169 self.on_change
170 .iter()
171 .filter(|c| c.applies_to(value))
172 .collect()
173 }
174
175 /// The most severe consequence of landing `value`, or `None` if there is
176 /// none. Allocates nothing — this runs per keystroke in an editor deciding
177 /// whether to arm a confirm.
178 pub fn severity_of(&self, value: &Value) -> Option<Severity> {
179 self.on_change
180 .iter()
181 .filter(|c| c.applies_to(value))
182 .map(|c| c.severity)
183 .max()
184 }
185}
186
187/// Guards that name a value the vocabulary doesn't have — a lint, run when an
188/// embedder loads its schema, not part of validation.
189///
190/// A guard is silent when it is wrong: `Consequence::when("none", …)` against a
191/// vocabulary spelling it `off` simply never fires, and the user commits the
192/// expensive change with no warning at all. Nothing else in the crate can
193/// notice, because a guard that matches nothing is indistinguishable from a
194/// guard for a value the user hasn't chosen yet.
195///
196/// Only `Some(Value::Str(_))` guards are checked: an unguarded consequence has
197/// no value to look up, and a bool or numeric guard is not a vocabulary term.
198/// A [retired](Term::retired) term counts as present — it is still a known
199/// value, and warning about one is exactly what a retirement wants.
200///
201/// ```
202/// use fig_schema::{Consequence, Term, guards_without_terms};
203///
204/// let terms = [Term::value("off"), Term::value("registry")];
205/// let declared = [
206/// Consequence::when("none", "History will be discarded."),
207/// Consequence::when("off", "History will be discarded."),
208/// ];
209/// assert_eq!(guards_without_terms(&declared, &terms), vec!["none"]);
210/// ```
211pub fn guards_without_terms<'a>(consequences: &'a [Consequence], terms: &[Term]) -> Vec<&'a str> {
212 consequences
213 .iter()
214 .filter_map(|c| match &c.when {
215 Some(Value::Str(s)) => Some(s.as_str()),
216 _ => None,
217 })
218 .filter(|s| !terms.iter().any(|t| t.value == *s))
219 .collect()
220}
221
222#[cfg(test)]
223mod tests {
224 use super::*;
225 use crate::path::PathPat;
226 use crate::vocab::Validate;
227
228 // The engine is generic over the embedder's constraint type; consequences
229 // need nothing from it, so a unit type stands in.
230 #[derive(Debug, Clone)]
231 struct NoConstraint;
232 impl Validate for NoConstraint {
233 fn validate(&self, _value: &Value) -> crate::Validation {
234 crate::Validation::Ok
235 }
236 }
237
238 fn rule(consequences: Vec<Consequence>) -> FieldRule<NoConstraint> {
239 FieldRule::new(PathPat::key("setting")).on_change_all(consequences)
240 }
241
242 #[test]
243 fn a_float_guard_matches_rather_than_being_skipped() {
244 // Rust's float parsing and float literals are both correctly rounded,
245 // so a document spelling `1.5`, `1.50` or `1.5e0` and a guard written
246 // `1.5` produce identical bits. A guard on a float field is therefore
247 // a real guard, not a coin toss — assert it fires rather than leaving
248 // the question open.
249 let r = rule(vec![Consequence::when(1.5, "The scale changes.")]);
250 assert_eq!(r.consequences_of(&Value::Float(1.5)).len(), 1);
251 assert_eq!(
252 r.consequences_of(&crate::FieldType::Float.coerce("1.50"))
253 .len(),
254 1,
255 );
256 assert!(r.consequences_of(&Value::Float(1.6)).is_empty());
257 }
258
259 #[test]
260 fn guard_matching_goes_through_eq_canonical_not_derived_equality() {
261 // `Int(1) == Uint(1)` is false under the derived comparison, and a
262 // document past `i64::MAX` is the one place fig writes `Uint`. Swapping
263 // `eq_canonical` for `==` would regress this silently, so the property
264 // is asserted rather than assumed.
265 let r = rule(vec![Consequence::when(1i64, "The count changes.")]);
266 assert_eq!(r.consequences_of(&Value::Uint(1)).len(), 1);
267 assert_eq!(
268 rule(vec![Consequence::when(Value::Uint(u64::MAX), "…")])
269 .consequences_of(&Value::Uint(u64::MAX))
270 .len(),
271 1,
272 );
273 // And the boundary the widening rule turns on is still not a match.
274 assert!(
275 rule(vec![Consequence::when(Value::Uint(1), "…")])
276 .consequences_of(&Value::Int(-1))
277 .is_empty()
278 );
279 }
280
281 #[test]
282 fn a_typoed_guard_is_caught_by_the_lint_because_nothing_else_would() {
283 let terms = [Term::value("off"), Term::value("registry")];
284 let declared = [
285 Consequence::always("The archive is rewritten."),
286 Consequence::when("none", "History will be discarded."),
287 Consequence::when(false, "…"),
288 Consequence::when("registry", "…"),
289 ];
290 // Only the string guard that names no term; the unguarded and the
291 // non-string ones have nothing to look up.
292 assert_eq!(guards_without_terms(&declared, &terms), vec!["none"]);
293 // A retired term is still a known value, so a guard on one is fine.
294 let retired = [Term::value("off").retired(true)];
295 assert!(guards_without_terms(&declared[3..], &terms).is_empty());
296 assert!(guards_without_terms(&[Consequence::when("off", "…")], &retired).is_empty());
297 }
298
299 #[test]
300 fn an_unguarded_and_a_matching_guarded_consequence_both_survive() {
301 // The merge bug this shape exists to avoid: severities merge by taking
302 // the worst, prose does not. Keeping only the more severe message would
303 // drop the sentence that explains the blanket cost.
304 let r = rule(vec![
305 Consequence::always("Every document is rewritten."),
306 Consequence::when("none", "Existing ids cannot be recovered.")
307 .severity(Severity::ConfirmExplicitly),
308 Consequence::when("registry", "Ids move into the registry."),
309 ]);
310 let hit = r.consequences_of(&Value::Str("none".into()));
311 assert_eq!(hit.len(), 2);
312 assert_eq!(hit[0].message, "Every document is rewritten.");
313 assert_eq!(hit[1].message, "Existing ids cannot be recovered.");
314 assert_eq!(
315 r.severity_of(&Value::Str("none".into())),
316 Some(Severity::ConfirmExplicitly)
317 );
318 // The other destination keeps the blanket one and its own, at the
319 // severity *it* declared rather than the worst on the field.
320 assert_eq!(r.consequences_of(&Value::Str("registry".into())).len(), 2);
321 assert_eq!(
322 r.severity_of(&Value::Str("registry".into())),
323 Some(Severity::Notice)
324 );
325 }
326
327 #[test]
328 fn asking_twice_about_one_value_answers_the_same_way_because_no_op_detection_is_the_hosts() {
329 // The test you might expect here — "a no-op re-set does not warn" — is
330 // unwritable in this crate, and that is the design, not a gap: there is
331 // no current value and no concept of absence to compare against. So
332 // assert the property that *does* hold and that the host's suppression
333 // depends on: the answer is a function of the destination alone.
334 // Without this, someone writes the straightforward version, finds they
335 // must add current-value tracking, and quietly reverses the decision.
336 let r = rule(vec![Consequence::when("off", "History will be discarded.")]);
337 let value = Value::Str("off".into());
338 let first = r.consequences_of(&value);
339 let second = r.consequences_of(&value);
340 assert_eq!(first, second);
341 assert_eq!(first.len(), 1);
342 assert_eq!(r.severity_of(&value), r.severity_of(&value));
343 }
344
345 #[test]
346 fn a_rule_declaring_nothing_has_no_consequences() {
347 let r: FieldRule<NoConstraint> = FieldRule::new(PathPat::key("title"));
348 assert!(r.consequences_of(&Value::Str("anything".into())).is_empty());
349 assert_eq!(r.severity_of(&Value::Str("anything".into())), None);
350 }
351
352 #[test]
353 fn severity_orders_ascending_so_max_picks_the_loudest() {
354 assert!(Severity::Notice < Severity::Confirm);
355 assert!(Severity::Confirm < Severity::ConfirmExplicitly);
356 }
357
358 #[test]
359 fn every_severity_round_trips_through_its_name() {
360 for severity in [
361 Severity::Notice,
362 Severity::Confirm,
363 Severity::ConfirmExplicitly,
364 ] {
365 assert_eq!(Severity::from_name(severity.name()), Some(severity));
366 }
367 assert_eq!(Severity::from_name("Confirm"), None);
368 }
369}