ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
use core::fmt::Display;

use super::*;
use crate::graphql::scalar::{F32, F64};

#[cfg(test)]
mod tests;

/// **THE WIDE DOOR** — one confidence THRESHOLD as a client writes it, before any width has been
/// chosen for it.
///
/// Two spellings are read and both are kept EXACTLY:
///
/// - a **JSON number** — `0.82` — which is the form an `f16`, `f32` or `f64` threshold arrives in,
///   and what this holds is the double the wire carried, unrounded;
/// - **decimal TEXT** — `"0.82"` — which is the form an exact base-ten confidence arrives in, and
///   what this holds is the literal the client wrote, character for character.
///
/// # Why the operand is not the COLUMN's width
///
/// A filter is one input object over every width a confidence measures in (see [`ConfidenceFilter`]),
/// so its operand cannot be the column's type — there is no column in sight when a client writes the
/// threshold. What resolves the width is the LOWERING: a `gte` crosses into the column's own carrier
/// at that carrier's own precision, one [`ConfidenceWire`] row per width, and the operand's job is to
/// reach that crossing with nothing lost on the way.
///
/// Both legs manage it. A double IS what a JSON number carries, so the number leg loses nothing by
/// definition; and the text leg keeps the literal rather than a parse of it, so a base-ten value with
/// more precision than a double can hold reaches an exact width intact. **A threshold a client wrote
/// as an `f32` widens into a double exactly and narrows back to the same `f32`** — the identity that
/// makes the number leg safe for the narrow widths, and it is IEEE's rather than this crate's: every
/// binary32 and every binary16 value is a binary64 value.
///
/// # The door does NOT move with a cargo feature
///
/// Neither leg names [`rust_decimal`](https://docs.rs/rust_decimal), and that is deliberate: what
/// the `rust_decimal` word buys is a confidence measured in `Decimal` — a CARRIER — and a build
/// declining the word must not thereby narrow the grammar a client writes against. So the text leg
/// is read, checked and kept in every build, and the decimal PARSE happens one layer down, in the
/// carrier's own [`ConfidenceWire`] row, which is gated on the word that supplies the type.
///
/// There is consequently nothing here to degrade when the word is off, which is the whole reason the
/// kernel is a literal rather than a decimal value.
///
/// # The text leg has NO exponent, and that is not a shortfall
///
/// `"1e-3"` is refused and `"0.001"` is not. An exponent buys no exactness a plain literal lacks —
/// every finite decimal has a plain spelling, and inside `[0.0, 1.0]` it is a short one — while
/// admitting one would put a second grammar between the client's digits and the interval check that
/// has to judge them EXACTLY. The number leg is where a client with an exponent in hand writes
/// `0.001`.
///
/// # Examples
///
/// ```
/// use ingraph::ConfidenceOperand;
///
/// // The two doors, and both refuse what a confidence is not.
/// assert!(ConfidenceOperand::number(0.82).is_ok());
/// assert!(ConfidenceOperand::decimal("0.82").is_ok());
///
/// assert!(ConfidenceOperand::number(1.5).is_err());
/// assert!(ConfidenceOperand::decimal("1.5").is_err());
/// assert!(ConfidenceOperand::decimal("half").is_err());
/// ```
#[derive(Clone, PartialEq)]
pub struct ConfidenceOperand(Reading);

/// Which door an operand came through, and what that door kept.
///
/// Private, and the two accessors above it are the whole of the surface: the arms are a fact about
/// the WIRE — whether a client wrote digits or a string — and a caller that wants the value asks for
/// it at a width.
#[derive(Clone, PartialEq)]
enum Reading {
  /// The JSON number leg: exactly the double the wire carried, already inside `[0.0, 1.0]`.
  Number(f64),
  /// The decimal-text leg: exactly the literal the client wrote, already checked against the
  /// grammar and the interval.
  Text(Box<str>),
}

/// **Why one wide-door operand was refused**, and there are exactly two reasons.
///
/// Both are the OPERAND's own — a value that is not a confidence in any width — so both are answered
/// at the scalar, before a column is in sight. What a WIDTH refuses is a third thing and has a type
/// of its own: [`UnrepresentableConfidence`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfidenceOperandError {
  /// The text was not a plain base-ten literal — digits, optionally a point and more digits.
  ///
  /// An exponent, a stray character and an empty string all land here, and so does a sign in front
  /// of anything but zero.
  Spelling,
  /// The value is not a number in the closed unit interval `[0.0, 1.0]`.
  ///
  /// A `NaN` and an infinity are refused by this clause too: neither is a number in the interval,
  /// and the constructor that keeps the interval is the same one every [`Confidence`] goes through.
  Interval,
}

impl Display for ConfidenceOperandError {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self {
      Self::Spelling => f.write_str(
        "a decimal confidence is written as plain base ten — digits, optionally a point and more \
         digits, with no exponent and no sign",
      ),
      Self::Interval => {
        f.write_str("a confidence is a number in the closed unit interval `[0.0, 1.0]`")
      }
    }
  }
}

impl core::error::Error for ConfidenceOperandError {}

impl ConfidenceOperand {
  /// The NUMBER leg: one threshold as the double a JSON number carries.
  ///
  /// `-0.0` is admitted and normalised to `+0.0`, which is [`ConfidenceCarrier`]'s own clause at the
  /// IEEE widths read one layer up: the two compare equal, so keeping both would make one value two
  /// operands.
  ///
  /// # Errors
  ///
  /// [`ConfidenceOperandError::Interval`] for a `NaN`, an infinity, or a value outside
  /// `[0.0, 1.0]`.
  pub fn number(value: f64) -> Result<Self, ConfidenceOperandError> {
    if value.is_nan() || !(0.0..=1.0).contains(&value) {
      return Err(ConfidenceOperandError::Interval);
    }
    Ok(Self(Reading::Number(value + 0.0)))
  }

  /// The TEXT leg: one threshold as the exact base-ten literal a client wrote.
  ///
  /// The literal is kept verbatim, so a width that can hold it exactly gets exactly it. The one
  /// normalisation is the sign, which is admitted only in front of a zero and dropped there — `-0`
  /// and `0` are one value, and the number leg treats them alike.
  ///
  /// # Errors
  ///
  /// [`ConfidenceOperandError::Spelling`] where the text is not a plain decimal literal, and
  /// [`ConfidenceOperandError::Interval`] where it is one and names a value outside `[0.0, 1.0]`.
  pub fn decimal(text: &str) -> Result<Self, ConfidenceOperandError> {
    let (negated, digits) = match text.strip_prefix('-') {
      Some(rest) => (true, rest),
      None => (false, text),
    };
    let (whole, fraction) = match digits.split_once('.') {
      Some((whole, fraction)) => (whole, fraction),
      None => (digits, ""),
    };
    // The grammar: at least one digit either side of a point that is written, and nothing else. A
    // trailing point is refused with the rest — `"1."` is a spelling this door has no reason to
    // carry, and refusing it keeps every literal here one that a decimal parser and a float parser
    // both read the same way.
    let spelled = !whole.is_empty()
      && whole.bytes().all(|byte| byte.is_ascii_digit())
      && (digits.find('.').is_none() || (!fraction.is_empty()))
      && fraction.bytes().all(|byte| byte.is_ascii_digit());
    if !spelled {
      return Err(ConfidenceOperandError::Spelling);
    }

    // The INTERVAL, judged on the digits themselves and therefore EXACTLY. A value below one has a
    // whole part of zero however many leading zeros it carries; a value that IS one has a whole part
    // of one and a fraction of nothing but zeros; everything else is outside. No parse stands
    // between the client's literal and this answer, which is what lets `"1.0000000000000000001"` be
    // refused where a double would have rounded it onto the endpoint and admitted it.
    let zeros = |part: &str| part.bytes().all(|byte| byte == b'0');
    let whole_is = whole.trim_start_matches('0');
    let inside = if whole_is.is_empty() {
      true
    } else {
      whole_is == "1" && zeros(fraction)
    };
    // A sign is a spelling of the same zero, and nothing else: `-0.5` is outside the interval.
    if !inside || (negated && !(zeros(whole) && zeros(fraction))) {
      return Err(ConfidenceOperandError::Interval);
    }
    Ok(Self(Reading::Text(Box::from(digits))))
  }

  /// The literal a TEXT operand carries, or [`None`] where the client wrote a JSON number.
  ///
  /// The exact spelling, which is what an exact width reads: see
  /// [`ConfidenceWire::read`](ConfidenceWire::read).
  #[inline]
  #[must_use]
  pub fn as_decimal(&self) -> Option<&str> {
    match &self.0 {
      Reading::Text(literal) => Some(literal),
      Reading::Number(_) => None,
    }
  }

  /// This operand AS A DOUBLE — the number leg verbatim, the text leg correctly rounded.
  ///
  /// Total, and the constructors are why: every text operand is a plain decimal literal inside
  /// `[0.0, 1.0]`, which [`f64`]'s own parser reads without failing and without overflowing.
  ///
  /// # It is the FLOAT WIDTHS' one road, and the rounding is single
  ///
  /// `f32` and `f16` both narrow from here rather than parsing the literal themselves, and that
  /// costs no accuracy: a double carries 53 significant bits where binary32 carries 24 and binary16
  /// carries 11, and a correctly-rounded conversion through an intermediate of at least `2p + 2`
  /// bits is indistinguishable from rounding the decimal straight to the target (53 ≥ 2·24 + 2 and
  /// 53 ≥ 2·11 + 2). So the text leg is the number leg with one exact step in front of it, at every
  /// binary width.
  #[inline]
  #[must_use]
  pub fn as_double(&self) -> f64 {
    match &self.0 {
      Reading::Number(double) => *double,
      Reading::Text(literal) => literal
        .parse()
        .expect("a confidence operand's text is a plain decimal literal inside [0.0, 1.0]"),
    }
  }
}

impl Display for ConfidenceOperand {
  /// The spelling the client wrote, which is what a refusal names it by.
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match &self.0 {
      Reading::Number(double) => write!(f, "{double}"),
      Reading::Text(literal) => f.write_str(literal),
    }
  }
}

impl core::fmt::Debug for ConfidenceOperand {
  /// The spelling AND the leg, and the QUOTING is what tells them apart — `ConfidenceOperand(0.5)`
  /// for a JSON number and `ConfidenceOperand("0.5")` for decimal text, exactly as the two arrive.
  ///
  /// Hand-written rather than derived for two reasons. The derive would name [`Reading`], which is a
  /// private type and no part of what a caller reasons in; and the two legs are two OPERANDS — a
  /// text `"0.1"` and a number `0.1` are not the same threshold at an exact width — so a rendering
  /// that hid which one this is would hide the one distinction the type exists to keep.
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match &self.0 {
      Reading::Number(double) => write!(f, "ConfidenceOperand({double})"),
      Reading::Text(literal) => write!(f, "ConfidenceOperand({literal:?})"),
    }
  }
}

/// A confidence at ONE WIDTH as the wire sees it — which roster scalar it is returned under, and how
/// it reads a wide-door operand.
///
/// # It is NOT one of the three carrier-axis readings
///
/// [`TextWire`](crate::TextWire), [`ScalarWire`](crate::ScalarWire) and
/// [`BytesWire`](crate::BytesWire) are keyed on a MARKER, because which name a filter publishes is a
/// property of a reading a field names. This one is keyed on the WIDTH, and carries no name at all:
/// there is one filter name for every confidence (see [`ConfidenceFilter`]) and the widths differ in
/// precision rather than in vocabulary.
///
/// # Sealed, because [`ConfidenceCarrier`] is
///
/// A width joins the confidence vocabulary by being MEASURED — see [`ConfidenceCarrier`], where the
/// seal and its argument live — and this trait's supertrait is that vocabulary, so nothing outside
/// this crate can implement either half. What IS open is the layer above: a type that wants a
/// confidence filter implements [`ScoreKind`], which asks for no width at all.
pub trait ConfidenceWire: crate::ConfidenceCarrier {
  /// The roster carrier a confidence of this width crosses OUT on — [`F32`], [`F64`], `F16`, `F128`.
  ///
  /// The retired `Score`, `ScoreF64`, `ScoreF16` and `ScoreF128` scalars are what this replaces, and
  /// the ruling behind it is that a named scalar has to say something the roster does not: an
  /// interval is a CONSTRUCTOR's promise and not a grammar, so `Score` published `0.82` under a name
  /// a client had to be told the meaning of, where `f32` publishes the same digits under the width
  /// every other single-precision column in the schema already uses.
  ///
  /// The interval did not go with the name. It is kept where it was always kept — at
  /// [`Confidence::new`], which every crossing in either direction goes through — and it is stated
  /// to a reader in the FIELD's own documentation rather than in a scalar's.
  type Carrier: From<Self> + Into<Self>;

  /// The roster's own word for this width, and what a refusal names.
  const WIDTH: &'static str;

  /// Read one wide-door operand AT THIS WIDTH, or refuse a value this width cannot hold.
  ///
  /// The binary widths refuse nothing here — every operand is a number in `[0.0, 1.0]` and every
  /// such number has a nearest value at every binary width — so their refusal is structurally
  /// impossible rather than merely unobserved. The exact width is the one that can refuse, and it
  /// refuses a literal carrying more precision than its scale admits, which is the honest answer:
  /// rounding it would answer a question the client did not ask.
  fn read(operand: &ConfidenceOperand) -> Option<Confidence<Self>>;
}

/// The two IEEE widths Rust ships, whose reading is one argument written twice: narrow the operand's
/// double to the width, then let the interval do what it always does.
///
/// The narrowing is the same conversion the roster's own `f32` scalar spends
/// ([`scalar::narrowed`](crate::graphql::scalar)), and at `f64` it is the identity — a JSON number IS
/// a double, so nothing moves at that width in either direction.
macro_rules! ieee_wire {
  ($( $ty:ty => $carrier:ty : $width:literal, narrow = $narrow:expr ),+ $(,)?) => {
    $(
      impl ConfidenceWire for $ty {
        type Carrier = $carrier;

        const WIDTH: &'static str = $width;

        #[inline]
        fn read(operand: &ConfidenceOperand) -> Option<Confidence<Self>> {
          #[allow(clippy::redundant_closure_call)]
          Confidence::new($narrow(operand.as_double()))
        }
      }
    )+
  };
}

ieee_wire!(
  f32 => F32 : "f32", narrow = (|wide: f64| wide as f32),
  f64 => F64 : "f64", narrow = core::convert::identity,
);

/// IEEE binary16, reached through the double for [`ConfidenceOperand::as_double`]'s measured reason
/// — 53 significant bits is more than the `2p + 2` a single rounding needs at eleven.
///
/// `half::f16::from_f64` is the crate's own round-to-nearest-even conversion. It saturates to an
/// infinity past `f16::MAX`, which no operand here can reach: the interval closed that door before
/// the width was in question.
#[cfg(feature = "half")]
impl ConfidenceWire for half::f16 {
  type Carrier = crate::graphql::scalar::F16;

  const WIDTH: &'static str = "f16";

  #[inline]
  fn read(operand: &ConfidenceOperand) -> Option<Confidence<Self>> {
    Confidence::new(half::f16::from_f64(operand.as_double()))
  }
}

/// The BASE-TEN width, and the ONE row whose two legs are two bodies rather than one.
///
/// A text operand is read `from_str_exact` — EXACTLY, so a literal carrying more precision than the
/// scale admits is refused rather than rounded away — and a number operand keeps the double's own
/// value through `from_f64_retain`, which is the most a number leg can honestly promise: a value a
/// JSON number could not carry intact was already lost before this crate saw it.
///
/// This is the width the text leg exists FOR, and the split is where that pays: `"0.1"` reaches a
/// decimal column as the decimal `0.1`, where `0.1` reaches it as the double that is not `0.1`.
#[cfg(feature = "rust_decimal")]
impl ConfidenceWire for rust_decimal::Decimal {
  type Carrier = crate::graphql::scalar::F128;

  const WIDTH: &'static str = "f128";

  fn read(operand: &ConfidenceOperand) -> Option<Confidence<Self>> {
    let decimal = match operand.as_decimal() {
      Some(literal) => rust_decimal::Decimal::from_str_exact(literal).ok()?,
      None => rust_decimal::Decimal::from_f64_retain(operand.as_double())?,
    };
    Confidence::new(decimal)
  }
}

/// **THE SCORE CAPABILITY** — what a [`ConfidenceFilter`] guards, and the axis the confidence family
/// widens along.
///
/// A type answers this trait by saying how ONE wide-door operand becomes a value of it, and that is
/// the whole of what a confidence filter needs of the thing it filters. Nothing here mentions a
/// width, a carrier vocabulary or an interval: those are [`Confidence`]'s answer to the question,
/// and a second answer is a second implementer rather than a change to this trait.
///
/// # Open where [`ConfidenceCarrier`] is sealed, and the split is the point
///
/// The WIDTH vocabulary is closed because a width is admitted by a MEASUREMENT this crate makes —
/// which of its values are not numbers, which two compare equal carrying different bits. A SCORE is
/// not admitted by any such measurement: it is a type that answers a threshold question, and the
/// framework has no way to be wrong about whether one does. So the filter binds this trait, one
/// blanket row carries every `Confidence<S>` into it, and a builtin that comes to serve as a score
/// joins by writing one impl — no row here, in the marker layer, or in either backend has to hear
/// about it.
///
/// # It is not [`WireScore`](crate::WireScore), which is the OTHER position
///
/// That trait is a search HIT's currency on the way out — what a `score:` row renders as — and it is
/// blanket over the output crossing. This one is an operand's road IN, at a filter. A type may
/// answer both, one, or neither, and the two never meet: a hit's score is not a column and a
/// column's confidence is not a hit.
///
/// # Examples
///
/// Every width of the framework's own confidence answers it, through one blanket row:
///
/// ```
/// use ingraph::{Confidence, ConfidenceOperand, ScoreKind};
///
/// let operand = ConfidenceOperand::decimal("0.82").expect("a confidence");
///
/// assert_eq!(
///   Confidence::<f32>::from_operand(&operand).expect("f32 holds it").get(),
///   0.82_f32
/// );
/// assert_eq!(
///   Confidence::<f64>::from_operand(&operand).expect("f64 holds it").get(),
///   0.82_f64
/// );
/// ```
///
/// A type that answers nothing is refused where the filter's crossing names it, and the note says
/// which row is missing:
///
/// ```compile_fail,E0277
/// struct Unscored;
///
/// fn scored<S: ingraph::ScoreKind>() {}
///
/// fn main() {
///   scored::<Unscored>();
/// }
/// ```
#[diagnostic::on_unimplemented(
  message = "`{Self}` is not a SCORE — nothing says what one confidence threshold means for it",
  label = "not a score",
  note = "a `ConfidenceFilter`'s operands are widthless (`ingraph::ConfidenceOperand`), so a type \
          reaches that filter only by saying how one operand crosses into it: write \
          `impl ingraph::ScoreKind for {Self}`, giving its `Error` and `from_operand`. \
          `ingraph::Confidence<S>` answers it at every width it measures in",
  note = "if `{Self}` is a STORAGE type standing in for a confidence column, the row belongs on the \
          storage type rather than on the column's: a crossing lands in the type the database \
          holds, and a declared converter (`<db>(into = …)`) is the other road — it \
          supplies the conversion at the call site and asks this trait for nothing"
)]
pub trait ScoreKind: Sized {
  /// Why an operand is not a value of this type.
  ///
  /// [`Display`], because the sentence reaches the client through `InputValueError::custom` at the
  /// wire and through a crossing refusal at the store — a person reads it either way.
  type Error: Display;

  /// Read one wide-door operand as a value of this type.
  ///
  /// # Errors
  ///
  /// Whatever this type refuses an operand with — for a [`Confidence`], a literal the width cannot
  /// hold exactly.
  fn from_operand(operand: &ConfidenceOperand) -> Result<Self, Self::Error>;
}

/// **What one WIDTH refuses a wide-door operand with**, and the only refusal a confidence crossing
/// has.
///
/// It names the operand as the client spelled it and the roster's word for the width that could not
/// hold it, which is the pair a caller needs: the same `"0.1000000000000000000000000000001"` is a
/// perfectly good `f32` threshold and is past a decimal's scale, so neither half of the sentence
/// stands without the other.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnrepresentableConfidence {
  width: &'static str,
  operand: Box<str>,
}

impl UnrepresentableConfidence {
  /// The roster's own word for the width that refused — `f32`, `f64`, `f16`, `f128`.
  #[inline]
  #[must_use]
  pub const fn width(&self) -> &'static str {
    self.width
  }

  /// The operand, as the client spelled it.
  #[inline]
  #[must_use]
  pub fn operand(&self) -> &str {
    &self.operand
  }
}

impl Display for UnrepresentableConfidence {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    write!(
      f,
      "`{}` is not a confidence this column can hold — it measures in `{}`, which cannot carry that \
       operand exactly",
      self.operand, self.width,
    )
  }
}

impl core::error::Error for UnrepresentableConfidence {}

/// **ONE ROW OVER THE WIDTH**, which is the same arrangement every other confidence row takes and
/// for the same measured reason: four rows would put four lines into rustc's *the following other
/// types implement trait `ScoreKind`* help, two of them riding a cargo feature, and a golden pinning
/// that block would then be green on one lane and red on another. One generic row prints as
/// `Confidence<S>` in every build.
///
/// The per-width behaviour is not lost with the list — it is [`ConfidenceWire`]'s, which is where a
/// reader asks what a width does with an operand.
impl<S: ConfidenceWire> ScoreKind for Confidence<S> {
  type Error = UnrepresentableConfidence;

  #[inline]
  fn from_operand(operand: &ConfidenceOperand) -> Result<Self, UnrepresentableConfidence> {
    S::read(operand).ok_or_else(|| UnrepresentableConfidence {
      width: S::WIDTH,
      operand: Box::from(operand.to_string()),
    })
  }
}

/// The CONFIDENCE filter — six comparison operators over a threshold, and ONE input object for every
/// width a confidence measures in.
///
/// # One name, one vocabulary — where the widths used to be four of each
///
/// `ScoreFilter`, `ScoreF64Filter`, `ScoreF16Filter` and `ScoreF128Filter` are what this replaces,
/// and they were four names because `Registry::create_type` panics on one GraphQL name held by two
/// Rust types — so `ScalarFilter<Confidence<f32>>` and `ScalarFilter<Confidence<f64>>` could not
/// share one however identical their field lists were. A NON-GENERIC filter has no such twin: there
/// is one Rust type, so there is one name and no registry question to answer.
///
/// What that buys a client is the thing the four names cost it. The vocabulary was word-for-word the
/// same at every width — the interval is what makes the order total, and the interval does not vary
/// — so four names published one vocabulary four times and asked a schema reader to notice they were
/// the same. `CountFilter` is the precedent read from the other side: a name that states a ROLE
/// rather than a Rust type, held by one input object that every cardinality question goes through.
///
/// # Six words, and the two that left are the two that could not be answered honestly
///
/// `in` and `notIn` are absent. A membership list over a continuous measurement is N exact
/// equalities against operands the client typed, each resolved at the COLUMN's width — so
/// `in: [0.7, 0.8]` matches only rows whose stored value is bit-identical to a narrowing the client
/// cannot see, and answers *no rows* to a question the caller believed they had asked. That is
/// [`QuantifiedFilter`](crate::QuantifiedFilter)'s argument at a different kind: **a schema
/// publishes only the words it can answer**.
///
/// `eq` and `ne` stay, and the difference is not special pleading. A confidence is frequently a
/// value a caller already HOLDS — an endpoint (`eq: 1.0`), a counted proportion a decimal column
/// stores exactly (`eq: "0.5"`) — and one equality against one operand is a question with one
/// answer the caller can predict from the operand's own spelling. A list multiplies that by its
/// length and hides which member matched.
///
/// The null test is not here either, and that is the framework's law rather than this kind's: it
/// lives in [`Nullable<ConfidenceFilter>`](Nullable) and nowhere else, so `isNull` against a
/// `NOT NULL` column is a type that does not exist rather than a query matching no rows.
///
/// # The OPERAND is widthless and the COLUMN is not
///
/// Every slot holds a [`ConfidenceOperand`] — a JSON number or decimal text, kept exactly — and the
/// width is chosen at the crossing, by the column's own carrier, through [`ScoreKind`]. So one
/// threshold is written once and means the same thing at every width it is asked against, and a
/// declaration that widens a column from `f32` to `f64` changes no schema and no query.
///
/// # Examples
///
/// ```
/// use ingraph::{ConfidenceFilter, ConfidenceOperand, GraphqlFilter};
///
/// let strong = ConfidenceFilter::new()
///   .with_gte(ConfidenceOperand::number(0.8).expect("a confidence"));
///
/// assert!(!GraphqlFilter::is_empty(&strong));
/// assert_eq!(strong.gte().map(ToString::to_string), Some("0.8".to_owned()));
/// ```
///
/// The two membership operators are absent from the TYPE, so asking one is a compile error at the
/// call site rather than a refusal at a crossing:
///
/// ```compile_fail,E0599
/// let _ = ingraph::ConfidenceFilter::new().with_in_([]);
/// ```
///
/// The positive twin, which must COMPILE — stable rustdoc runs a `compile_fail` block just far
/// enough to see it fail and never checks why, so the pair shares its call shape and one half has to
/// be positive:
///
/// ```
/// use ingraph::{ConfidenceFilter, ConfidenceOperand};
///
/// let _ = ConfidenceFilter::new().with_lt(ConfidenceOperand::number(0.5).expect("a confidence"));
/// ```
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ConfidenceFilter {
  pub(crate) eq: Option<ConfidenceOperand>,
  pub(crate) ne: Option<ConfidenceOperand>,
  pub(crate) gt: Option<ConfidenceOperand>,
  pub(crate) gte: Option<ConfidenceOperand>,
  pub(crate) lt: Option<ConfidenceOperand>,
  pub(crate) lte: Option<ConfidenceOperand>,
}

impl ConfidenceFilter {
  /// The empty filter — no operator set.
  #[inline]
  pub const fn new() -> Self {
    Self {
      eq: None,
      ne: None,
      gt: None,
      gte: None,
      lt: None,
      lte: None,
    }
  }

  /// True while NO operator slot is set — so a lowering would emit nothing for this field.
  ///
  /// Inherent, not the backend traits' provided `is_empty`, for [`ScalarFilter::is_empty`]'s reason:
  /// "is anything set" is a property of the FILTER, identical on every backend, and asking it should
  /// not make a caller name a dialect.
  #[inline]
  pub const fn is_empty(&self) -> bool {
    self.eq.is_none()
      && self.ne.is_none()
      && self.gt.is_none()
      && self.gte.is_none()
      && self.lt.is_none()
      && self.lte.is_none()
  }

  opt_accessor!(eq: ConfidenceOperand => with_eq, set_eq, maybe_eq, update_eq);
  opt_accessor!(ne: ConfidenceOperand => with_ne, set_ne, maybe_ne, update_ne);
  opt_accessor!(gt: ConfidenceOperand => with_gt, set_gt, maybe_gt, update_gt);
  opt_accessor!(gte: ConfidenceOperand => with_gte, set_gte, maybe_gte, update_gte);
  opt_accessor!(lt: ConfidenceOperand => with_lt, set_lt, maybe_lt, update_lt);
  opt_accessor!(lte: ConfidenceOperand => with_lte, set_lte, maybe_lte, update_lte);

  /// Convert every set operand with `f`, keeping the operator set exactly as it stands.
  ///
  /// The primitive the CROSSING is built on, and it lands on [`ScalarFilter`] rather than on this
  /// type: the operands stop being widthless the moment they cross, so what comes out is an ordinary
  /// ordering filter over the column's own storage type — with `in`/`not_in` empty, this kind having
  /// no slot for either.
  ///
  /// That is what lets one confidence column reach every backend through the machinery every other
  /// scalar column reaches it through, with no comparison kind of its own.
  ///
  /// # Errors
  ///
  /// Whatever `f` refuses an operand with, the first refusal winning.
  pub fn try_map<U, E, F>(self, mut f: F) -> Result<ScalarFilter<U>, E>
  where
    F: FnMut(ConfidenceOperand) -> Result<U, E>,
  {
    let mut crossed = |slot: Option<ConfidenceOperand>| match slot {
      Some(operand) => f(operand).map(Some),
      None => Ok(None),
    };
    Ok(
      ScalarFilter::new()
        .maybe_eq(crossed(self.eq)?)
        .maybe_ne(crossed(self.ne)?)
        .maybe_gt(crossed(self.gt)?)
        .maybe_gte(crossed(self.gte)?)
        .maybe_lt(crossed(self.lt)?)
        .maybe_lte(crossed(self.lte)?),
    )
  }
}

/// The bound's row: [`try_map`](ConfidenceFilter::try_map) itself, reached where the kind is a
/// parameter rather than a spelling — which is what a DECLARED converter's crossing names.
impl<U> TryMapFilter<ConfidenceOperand, U> for ConfidenceFilter {
  type Mapped = ScalarFilter<U>;

  #[inline]
  fn try_map_filter<E, F>(self, f: F) -> Result<Self::Mapped, E>
  where
    F: FnMut(ConfidenceOperand) -> Result<U, E>,
  {
    self.try_map(f)
  }
}

impl GraphqlFilter for ConfidenceFilter {
  #[inline]
  fn is_empty(&self) -> bool {
    Self::is_empty(self)
  }
}

/// The bound's row: `new()` and the inherent `with_eq`, reached where the kind is a parameter rather
/// than a spelling.
impl EqualsFilter<ConfidenceOperand> for ConfidenceFilter {
  #[inline]
  fn equals(value: ConfidenceOperand) -> Self {
    Self::new().with_eq(value)
  }
}

/// A confidence THRESHOLD in the closed unit interval `[0.0, 1.0]`, written either way a client
/// has one.
///
/// A JSON number — `0.82`, and `1` is the same operand as `1.0` — or DECIMAL TEXT — `"0.82"`, which
/// is exact base ten and is what to write when the value is a counted proportion rather than an
/// estimate: `0.1` has no double that IS it. An exponent is not read; write `0.001` rather than
/// `1e-3`, in either form.
///
/// An operand outside the interval is REFUSED and never clamped. `gte: 1.5` is an error rather than
/// the rows matching `gte: 1.0`, because a substituted operand is a wrong result set reported as a
/// right one.
///
/// It carries no WIDTH, and that is deliberate: the same threshold is asked against a column
/// measured in `f32`, `f64`, `f16` or exact base ten, and the column's own precision is what reads
/// it. So a schema that widens a confidence column changes neither this operand nor the query that
/// wrote it.
// # The two legs are ONE notion of validity
//
// `parse` and `is_valid` read through the same two constructors, which is the property every scalar
// in this crate has to have and async-graphql's default does not: its `is_valid` answers `true` for
// every value, so a scalar that refuses in `parse` alone ships a validator admitting what its own
// parser rejects.
//
// # The refusal names WHICH clause failed
//
// `ConfidenceOperandError` has two arms and both reach the client verbatim, because the two are
// different things for a caller to do about: a spelling refusal is a query to fix and an interval
// refusal is a threshold to fix. A single *expected type* would have said neither.
#[cfg(feature = "async-graphql")]
#[async_graphql::Scalar(name = "ConfidenceOperand")]
impl async_graphql::ScalarType for ConfidenceOperand {
  fn parse(value: async_graphql::Value) -> async_graphql::InputValueResult<Self> {
    match &value {
      async_graphql::Value::String(text) => {
        Self::decimal(text).map_err(async_graphql::InputValueError::custom)
      }
      async_graphql::Value::Number(number) => match number.as_f64() {
        Some(wide) => Self::number(wide).map_err(async_graphql::InputValueError::custom),
        None => Err(async_graphql::InputValueError::custom(
          ConfidenceOperandError::Interval,
        )),
      },
      _ => Err(async_graphql::InputValueError::expected_type(value)),
    }
  }

  #[inline]
  fn is_valid(value: &async_graphql::Value) -> bool {
    match value {
      async_graphql::Value::String(text) => Self::decimal(text).is_ok(),
      async_graphql::Value::Number(number) => number
        .as_f64()
        .is_some_and(|wide| Self::number(wide).is_ok()),
      _ => false,
    }
  }

  /// The spelling the operand ARRIVED in, so a rendered filter round-trips through its own parser.
  ///
  /// A number leg renders a number and a text leg renders text, which is what makes the two legs two
  /// operands rather than one operand with a rendering choice: an exact base-ten threshold handed
  /// back as a double would be handed back as a value that is not it, and that is the whole reason
  /// the text leg exists.
  fn to_value(&self) -> async_graphql::Value {
    match &self.0 {
      Reading::Number(double) => async_graphql::Value::Number(
        async_graphql::Number::from_f64(*double).expect("a confidence operand is finite"),
      ),
      Reading::Text(literal) => async_graphql::Value::String(literal.to_string()),
    }
  }
}

// The wire face, and it is `filter_input_object!`'s because this kind has nothing to be generic over
// — the same position `BooleanFilter` is in, reached by the opposite road. The boolean has one
// operand type because `bool` is the only type it guards; this one has one because the operand is
// deliberately WIDTHLESS, and the column's width is resolved a layer below the wire.
//
// The name is SPELLED rather than derived, as every Pascal row's is: a derivation runs through a
// `#[Scalar(name = …)]` literal, and a filter whose operand scalar is a different type has no such
// attribute of its own to derive from.
#[cfg(feature = "async-graphql")]
filter_input_object!(ConfidenceFilter : "ConfidenceFilter" {
  bare eq: ::core::option::Option<ConfidenceOperand> => "eq",
  ne: ::core::option::Option<ConfidenceOperand> => "ne",
  gt: ::core::option::Option<ConfidenceOperand> => "gt",
  gte: ::core::option::Option<ConfidenceOperand> => "gte",
  lt: ::core::option::Option<ConfidenceOperand> => "lt",
  lte: ::core::option::Option<ConfidenceOperand> => "lte",
});