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
//! The [`LanguageId`] composite: the four seats, the composition rules that fill them, the operand
//! its wire face crosses on, and the filter that guards its four columns.

use core::{fmt, str::FromStr};

use crate::{
  CompositeFilterMarker, CompositeMarker, DefaultMarker, Nullable, ScalarFilter, ToGraphqlInput,
};
use smol_bytes::Utf8Bytes;

use super::{
  Language, LanguageWire, ParseLanguageError, ParseRegionError, ParseScriptSubtagError, Region,
  RegionWire, ScriptSubtag, ScriptSubtagWire, registry,
};
use crate::graphql::filter::opt_accessor;

#[cfg(feature = "sqlx")]
mod comparison;
mod storage;

#[cfg(test)]
mod tests;

#[cfg(feature = "sqlx")]
pub use comparison::{LanguageIdCrossingError, SqlLanguageIdComparison};
pub use storage::LanguageIdColumnError;
/// Crate-internal: the sub-document reader [`DetectedLanguage`](super::DetectedLanguage)'s own
/// MongoDB row shares, its four keys being spliced into the SAME top-level document rather than
/// nested under one of their own — see `detected::storage`'s [`MongoCarrier`](crate::MongoCarrier)
/// row for why, and its [`MongoExtract`](crate::query::mongo::MongoExtract) row for the read.
#[cfg(feature = "mongo")]
pub(crate) use storage::document_seats;

/// A whole language identity — what UTS-35 calls a *unicode language id* and what a track's
/// metadata actually carries: `de`, `zh-Hans`, `en-US`, `sr-Cyrl-RS`, `en-US-x-lorem`.
///
/// FOUR seats, and the fourth is what makes the type lossless:
///
/// ```text
///   language   Language        always present — a tag with no language is not a tag
///   script     Option<ScriptSubtag>  absent where none was declared, or where the language
///                                implies it
///   region     Option<Region>  absent where none was declared
///   rest       Option<…>       everything past the region, VERBATIM
/// ```
///
/// # The composition rules, and every one of them is the registry's
///
/// | sent | held | the rule |
/// |---|---|---|
/// | `zh_Hans_CN` | `zh-Hans-CN` | `_` is read as `-`, which is what a filename-safe tag uses |
/// | `en-Latn` | `en` | `en` implies `Latn`, so declaring it says nothing — `Suppress-Script` |
/// | `zh-Hans` | `zh-Hans` | `zh` implies NO script, so the declaration is the whole content |
/// | `i-klingon` | `tlh` | a grandfathered tag, folded by its `Preferred-Value` |
/// | `GER-latn-de` | `de-DE` | each seat's own door, then the suppression |
///
/// **The `Suppress-Script` fold is the one that earns its keep**, and the pair above is why: it
/// removes a subtag that carries no information (`en-Latn` and `en` are the same identity) and
/// leaves alone one that carries all of it (`zh-Hans` and `zh-Hant` are two identities). A fold
/// spelled by hand would have had to decide which languages imply which scripts; this one reads a
/// column of a vendored file, so the answer is right for all 134 of them and stays right when the
/// registry moves.
///
/// # `rest` is LOSSLESS and has NO filter word, which is one decision rather than two
///
/// Everything past the region — variants (`en-US-posix`), extensions (`de-u-co-phonebk`), private
/// use (`en-x-lorem`) — is held VERBATIM, rendered back verbatim, and counts towards equality. It
/// is not parsed, not folded, and not case-normalised.
///
/// So `en-US-x-Foo` and `en-US-x-foo` are TWO values here, where RFC 5646's own canonical form would
/// lower-case both. That is the price of the seat being lossless rather than a defect in it: a
/// private-use sequence's meaning belongs to the private party that wrote it, and this type cannot
/// know that its case is insignificant. The tail is carried exactly as the file spelled it, and a
/// caller comparing tails as identifiers gets what the file said.
///
/// **The tail has no filter word**, and that follows from the same fact. There is nothing here that
/// could be asked honestly: `contains` over a text seat holding a mixture of three grammars would
/// answer questions about spelling rather than about identity, which is the single-text-column game
/// this type's four columns exist instead of. Asking about a WHOLE identity is what the four
/// identity words do, and they carry the tail with them.
///
/// **The envelope the tail is checked against is deliberately loose**: each of its subtags must be
/// one to eight ASCII alphanumeric characters, which is the outer shape of every variant, extension
/// and private-use subtag together. `en-USA` is admitted, though `USA` is not a legal variant,
/// because a container writes what its muxer believed and a metadata layer's job is to carry it —
/// the same posture that admits an unregistered language subtag.
///
/// # An extlang has no seat, so it rides the tail — and takes the rest of the tag with it
///
/// `zh-yue` holds `zh` with a tail of `yue`, because `yue` is three letters and a script is four
/// while a region is two or three DIGITS. That is the ruled roster doing what it says: the seats are
/// language, script and region, and BCP 47's extlang position is none of them.
///
/// The consequence is worth stating rather than discovering: the tail is a TAIL, so once a subtag
/// falls into it every later subtag does too. `zh-yue-Hant-HK` holds `zh` with a tail of
/// `yue-Hant-HK` — the script and region are IN the tail, and no component filter reaches them. The
/// tag round-trips exactly, and `{ language: { eq: zh } }` still finds it, which is the question the
/// ruling names. Filtering its script is what is lost, and a `zh-Hant-HK` tag — which is what a
/// well-formed file writes — has that filterable.
///
/// # Equality is the four seats, so it is the CANONICAL identity
///
/// `GER-latn-de` and `de-DE` are one value, because each seat folded before it was filled and the
/// suppression then removed the script. That is what makes a stored row and a query operand meet:
/// four columns hold the canonical parts, and a query built from any spelling of the same identity
/// binds the same four.
///
/// It is EQUALITY of identities and not of languages, which the same pair says from the other side:
/// `de` and `de-DE` are two values, because one names a region and the other does not. Asking about
/// the language they share is the component facet's business, not this one's.
///
/// # Ordering is the four seats in order, and it means what a text sort means
///
/// [`Ord`] is derived, so it compares the language first, then the script, then the region, then
/// the tail — each alphabetically, each absent sorting before present. It is a total, stable order
/// and therefore a usable cursor key, and it is nothing else: `de-AT` sorts before `de-DE` because
/// `A` sorts before `D`.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LanguageId {
  language: Language,
  script: Option<ScriptSubtag>,
  region: Option<Region>,
  rest: Option<Utf8Bytes>,
}

impl LanguageId {
  /// Read a whole tag, WIDE — any case, `_` or `-`, grandfathered or composed.
  ///
  /// The one door in, as each seat's own `new` is for its part.
  ///
  /// # The order the rules fire in
  ///
  /// 1. **`_` becomes `-`.** A filename-safe tag (`zh_Hans_CN`) is the same tag.
  /// 2. **The GRANDFATHERED table**, over the whole tag, case-folded. `i-klingon` is `tlh` and
  ///    `zh-guoyu` is `cmn`. Five grandfathered tags name no replacement, and those fall through to
  ///    the ordinary parse — where two of them (`cel-gaulish`, `zh-min`) turn out to be ordinary
  ///    compositions and the three beginning `i-` are refused, a one-letter primary subtag being
  ///    outside the grammar.
  /// 3. **The SEATS, positionally.** The first subtag is the language. A four-letter subtag next is
  ///    the script; a two-letter or three-digit one after that is the region; everything from the
  ///    first subtag that is neither is the tail.
  /// 4. **The SUPPRESSION.** A declared script the language already implies is dropped.
  ///
  /// # Errors
  ///
  /// [`ParseLanguageIdError`], naming the seat that refused and carrying its own error — so a
  /// client sending `e-US` is told what a language subtag is, by the type that knows.
  ///
  /// A seat is only ASKED about a subtag of its own shape, so the shape test and the seat's grammar
  /// cannot disagree: `zh-Hans-XYZ` never reaches the region door at all, `XYZ` being neither two
  /// letters nor three digits, and the tail's looser envelope takes it.
  pub fn new(text: &str) -> Result<Self, ParseLanguageIdError> {
    if text.is_empty() {
      return Err(ParseLanguageIdError::Empty);
    }

    // The separator fold happens FIRST and for the whole tag, so every rule below reads one
    // spelling. It is the only place this type rewrites its input outside a seat's own door.
    let normalized;
    let tag = if text.contains('_') {
      normalized = text.replace('_', "-");
      normalized.as_str()
    } else {
      text
    };

    if let Some(preferred) = grandfathered(tag) {
      // A `Preferred-Value` is always an ordinary composed tag — `tlh`, `cmn`, `en-GB-oxendict` —
      // so this recurses exactly once and lands in `composed` below.
      return Self::composed(preferred);
    }

    Self::composed(tag)
  }

  /// The three seats and the tail, read positionally out of a normalized tag.
  fn composed(tag: &str) -> Result<Self, ParseLanguageIdError> {
    let parts: Vec<&str> = tag.split('-').collect();

    if parts.iter().any(|part| part.is_empty()) {
      return Err(ParseLanguageIdError::EmptySubtag);
    }

    let language = Language::new(parts[0]).map_err(ParseLanguageIdError::Language)?;
    let mut at = 1;

    let script = match parts.get(at) {
      Some(part) if script_shaped(part) => {
        at += 1;
        Some(ScriptSubtag::new(part).map_err(ParseLanguageIdError::ScriptSubtag)?)
      }
      _ => None,
    };

    let region = match parts.get(at) {
      Some(part) if region_shaped(part) => {
        at += 1;
        Some(Region::new(part).map_err(ParseLanguageIdError::Region)?)
      }
      _ => None,
    };

    // The tail is a contiguous SUFFIX of the tag, so it is SLICED rather than rebuilt from the
    // parts: each consumed subtag cost its own length plus the separator after it, so the sum is
    // exactly where the tail begins. Slicing is what makes "verbatim" true of the separators too.
    let consumed: usize = parts[..at].iter().map(|part| part.len() + 1).sum();
    let rest = match consumed < tag.len() {
      true => Some(tail(&tag[consumed..])?),
      false => None,
    };

    Ok(Self {
      // The SUPPRESSION, and it is applied here rather than at `ScriptSubtag`'s door because it is
      // a fact
      // about the PAIR: a script means nothing beside a language that implies it, and everything
      // beside one that does not.
      script: match (&script, language.suppressed_script()) {
        (Some(declared), Some(implied)) if declared.as_str() == implied => None,
        _ => script,
      },
      language,
      region,
      rest,
    })
  }

  /// A tag from its four parts, with the suppression applied.
  ///
  /// The route a caller building an identity takes, where [`new`](Self::new) is the route a TEXT
  /// takes. It is total: every part has already been through its own door, and the tail is the one
  /// seat with nothing to check.
  ///
  /// The suppression still fires, which is what keeps the two routes in agreement — a `LanguageId`
  /// built from `en` and `Latn` is the same value as one parsed from `"en-Latn"`, and both are `en`.
  #[must_use]
  pub fn compose(
    language: Language,
    script: Option<ScriptSubtag>,
    region: Option<Region>,
    rest: Option<Utf8Bytes>,
  ) -> Self {
    Self {
      script: match (&script, language.suppressed_script()) {
        (Some(declared), Some(implied)) if declared.as_str() == implied => None,
        _ => script,
      },
      language,
      region,
      rest,
    }
  }

  /// The language, which every identity has.
  #[inline]
  #[must_use]
  pub const fn language(&self) -> &Language {
    &self.language
  }

  /// The script, where one was declared and the language does not already imply it.
  #[inline]
  #[must_use]
  pub const fn script(&self) -> Option<&ScriptSubtag> {
    self.script.as_ref()
  }

  /// The region, where one was declared.
  #[inline]
  #[must_use]
  pub const fn region(&self) -> Option<&Region> {
    self.region.as_ref()
  }

  /// Everything past the region, verbatim — variants, extensions and the private-use sequence.
  #[inline]
  #[must_use]
  pub const fn rest(&self) -> Option<&Utf8Bytes> {
    self.rest.as_ref()
  }
}

/// The widest subtag a tail may hold — the outer envelope of every variant, extension and
/// private-use subtag BCP 47 defines.
const TAIL_SUBTAG_MAX: usize = 8;

/// One tail through its envelope, held verbatim.
///
/// THE one authority for what a tail may be, read by the tag parser above and by the column decode
/// next door — so a tail that arrives as the far end of a tag and one that arrives as a column of
/// its own are admitted by the same rule.
///
/// The envelope is deliberately LOOSE: one to eight ASCII alphanumeric characters per subtag, which
/// is the outer shape of every variant, extension and private-use subtag together rather than any
/// one of their grammars. See [`LanguageId`], where the reason is the same one that admits an
/// unregistered language subtag.
pub(super) fn tail(text: &str) -> Result<Utf8Bytes, ParseLanguageIdError> {
  for part in text.split('-') {
    if part.is_empty() {
      return Err(ParseLanguageIdError::EmptySubtag);
    }
    if part.len() > TAIL_SUBTAG_MAX {
      return Err(ParseLanguageIdError::TailWidth);
    }
    if let Some(outside) = part
      .chars()
      .find(|character| !character.is_ascii_alphanumeric())
    {
      return Err(ParseLanguageIdError::Tail(outside));
    }
  }

  Ok(Utf8Bytes::from(text))
}

/// The widest whole tag the registry grandfathered, in bytes.
///
/// Nothing wider can be one, so nothing wider is looked up — which is what lets the case fold for
/// that lookup use a stack buffer rather than allocating a lower-cased copy of every tag that comes
/// through the door. `the_grandfathered_table_fits_the_lookup_buffer` is the pin that keeps the
/// shortcut from silently missing a tag the registry adds.
const GRANDFATHERED_MAX: usize = 16;

/// The replacement the registry names for a grandfathered tag, or [`None`] for a tag that is not
/// grandfathered or is grandfathered without one.
///
/// The five with no replacement answer [`None`] here and fall through to the ordinary parse, which
/// is the honest handling: two of them ARE ordinary compositions read subtag by subtag, and the
/// three beginning `i-` are refused by the language door for a reason it can state.
fn grandfathered(tag: &str) -> Option<&'static str> {
  if tag.len() > GRANDFATHERED_MAX {
    return None;
  }

  let mut lowered = [0u8; GRANDFATHERED_MAX];
  for (at, byte) in tag.as_bytes().iter().enumerate() {
    lowered[at] = byte.to_ascii_lowercase();
  }

  // SAFETY: `tag` is a `&str` and an ASCII case fold maps each of its bytes to a byte of the same
  // width and validity — a non-ASCII byte is above `0x7F` and is left alone — so the prefix written
  // above is the same UTF-8 sequence with some ASCII letters re-cased.
  let lowered = unsafe { core::str::from_utf8_unchecked(&lowered[..tag.len()]) };

  registry::grandfathered_preferred(lowered)
}

/// Is this subtag in the SCRIPT position's shape — exactly four ASCII letters?
fn script_shaped(part: &str) -> bool {
  part.len() == 4
    && part
      .chars()
      .all(|character| character.is_ascii_alphabetic())
}

/// Is this subtag in the REGION position's shape — two ASCII letters, or three ASCII digits?
fn region_shaped(part: &str) -> bool {
  let letters = part.len() == 2
    && part
      .chars()
      .all(|character| character.is_ascii_alphabetic());
  let digits = part.len() == 3 && part.chars().all(|character| character.is_ascii_digit());

  letters || digits
}

/// The canonical spelling: the seats that are filled, in order, joined by `-`.
///
/// The inverse of [`FromStr`] over canonical text, which is what makes it usable as a cursor and as
/// the `tag` field a client reads back into a filter operand.
impl fmt::Display for LanguageId {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.write_str(self.language.as_str())?;

    if let Some(script) = &self.script {
      write!(f, "-{script}")?;
    }
    if let Some(region) = &self.region {
      write!(f, "-{region}")?;
    }
    if let Some(rest) = &self.rest {
      write!(f, "-{}", rest.as_str())?;
    }

    Ok(())
  }
}

/// The canonical tag, in quotes — not the four seats, which would make an assertion message four
/// times longer than the value it is about.
impl fmt::Debug for LanguageId {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(f, "LanguageId({:?})", self.to_string())
  }
}

impl FromStr for LanguageId {
  type Err = ParseLanguageIdError;

  #[inline]
  fn from_str(text: &str) -> Result<Self, Self::Err> {
    Self::new(text)
  }
}

/// A tag with no other seats filled — the shape a bare language subtag composes to.
impl From<Language> for LanguageId {
  #[inline]
  fn from(language: Language) -> Self {
    Self {
      language,
      script: None,
      region: None,
      rest: None,
    }
  }
}

/// A string does not name a language identity.
///
/// The three seat variants CARRY the seat's own error rather than restating it, which is what keeps
/// one grammar per subtag kind: a client sending `zh-Hans-XYZ` is told that a region written in
/// letters is exactly two, by [`Region`]'s own words.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ParseLanguageIdError {
  /// Nothing was sent — an ABSENT identity rather than a malformed one, whose home is a `NULL`
  /// column.
  Empty,
  /// A subtag between two separators is empty: `en--US`, or a tag with a trailing `-`.
  EmptySubtag,
  /// The first subtag is not a language. This is where `i-default` and `i-mingo` land — a
  /// one-letter primary subtag is outside the grammar, and those two are grandfathered tags the
  /// registry names no replacement for.
  Language(ParseLanguageError),
  /// A subtag in the script position is four letters and still not a script. Unreachable today, the
  /// position test being the same width and alphabet the script door checks; it is propagated
  /// rather than unwrapped so that a widened position test cannot become a panic.
  ScriptSubtag(ParseScriptSubtagError),
  /// A subtag in the region position is not a region, for the same reason and with the same
  /// posture.
  Region(ParseRegionError),
  /// A tail subtag holds a character that is neither an ASCII letter nor an ASCII digit, carrying
  /// the first one found.
  Tail(char),
  /// A tail subtag is more than eight characters, which no variant, extension or private-use
  /// subtag is.
  TailWidth,
}

impl fmt::Display for ParseLanguageIdError {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      Self::Empty => {
        f.write_str("a language tag opens with a language subtag, and nothing was sent")
      }
      Self::EmptySubtag => f.write_str("a language tag has no empty subtag between its separators"),
      Self::Language(refused) => write!(f, "the tag's language subtag is not one: {refused}"),
      Self::ScriptSubtag(refused) => write!(f, "the tag's script subtag is not one: {refused}"),
      Self::Region(refused) => write!(f, "the tag's region subtag is not one: {refused}"),
      Self::Tail(outside) => write!(
        f,
        "a variant, extension or private-use subtag is letters and digits, so `{outside}` is not \
         one of its characters"
      ),
      Self::TailWidth => {
        f.write_str("a variant, extension or private-use subtag is at most eight characters")
      }
    }
  }
}

impl core::error::Error for ParseLanguageIdError {
  fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
    match self {
      Self::Language(refused) => Some(refused),
      Self::ScriptSubtag(refused) => Some(refused),
      Self::Region(refused) => Some(refused),
      Self::Empty | Self::EmptySubtag | Self::Tail(_) | Self::TailWidth => None,
    }
  }
}

/// A whole identity, on its way IN — the carrier the identity axis's four operators cross on.
///
/// A type of its own rather than [`LanguageId`] itself, and GraphQL's own namespace is what forces
/// it: objects and input types share one, so the scalar a client SENDS cannot be spelled
/// `LanguageId` while an object of that name is published. Every operand newtype in a declaring
/// crate states the same argument for the same reason.
///
/// Transparent in both directions: it holds a [`LanguageId`] that has already been validated, so
/// [`ToGraphqlInput`]'s crossing off it is [`Infallible`](core::convert::Infallible). Every refusal
/// happens at the scalar's own `parse`, which is the one door a wire value comes through.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LanguageIdOperand(LanguageId);

impl LanguageIdOperand {
  /// Wrap an identity as an operand.
  #[inline]
  #[must_use]
  pub const fn new(id: LanguageId) -> Self {
    Self(id)
  }

  /// The wrapped identity.
  #[inline]
  #[must_use]
  pub fn get(&self) -> &LanguageId {
    &self.0
  }
}

impl From<LanguageId> for LanguageIdOperand {
  #[inline]
  fn from(id: LanguageId) -> Self {
    Self(id)
  }
}

impl From<LanguageIdOperand> for LanguageId {
  #[inline]
  fn from(operand: LanguageIdOperand) -> Self {
    operand.0
  }
}

impl ToGraphqlInput for LanguageId {
  type Input = LanguageIdOperand;
  type Error = core::convert::Infallible;

  #[inline]
  fn cross(input: Self::Input) -> Result<Self, Self::Error> {
    Ok(input.into())
  }

  #[inline]
  fn carry(operand: &Self) -> Self::Input {
    LanguageIdOperand::new(operand.clone())
  }
}

/// **The crossing OUT, and it is NOT the operand's type** — which is the whole asymmetry the two
/// namespaces force.
///
/// A client SENDS a `LanguageIdOperand`, which is a scalar holding the canonical tag, and RECEIVES a
/// `LanguageId`, which is the `#[Object]` published next door: five fields, the four seats plus the
/// rendering that spells them. So this row hands back a BORROW of the value the row holds and lets
/// that object resolve it, where [`ToGraphqlInput`] above has to wrap.
///
/// The pair is what makes the identity a round trip rather than half of one: the object's `tag` field
/// is the operand's own text, so a client reads a tag out of one and writes it back into the other.
///
/// Without this row a declaration storing a `LanguageId` could publish NOTHING — an emitted face
/// returns `<LanguageId as ToGraphqlOutput>::Output<'_>`, so the absence is `E0277` at the face and
/// not at the column.
impl crate::ToGraphqlOutput for LanguageId {
  type Output<'a> = &'a Self;

  #[inline]
  fn to_graphql_output(marked: &Self) -> &Self {
    marked
  }
}

/// What guards a [`LanguageId`] column — [`Language`]'s row, and the same reading of it: an
/// identity stores every field it declares, so the two seats name one predicate.
///
/// [`Language`]: super::Language
impl CompositeFilterMarker for LanguageId {
  type Filter = LanguageIdFilter;
  type ColumnFilter = LanguageIdFilter;
}

/// The interpretation a [`LanguageId`] field is read under — [`Language`]'s reading, and this crate
/// no longer mints either: an identity occupies four columns OF ITS OWN, so all four can be absent
/// together, which is exactly the VALUE family [`CompositeMarker`] names — a track nobody tagged is
/// not a track tagged `und`.
///
/// [`Language`]: super::Language
impl DefaultMarker for LanguageId {
  type Marker = CompositeMarker<LanguageId>;
}

/// The filter that guards a [`LanguageId`] column: the whole IDENTITY, and each COMPONENT that has
/// a column of its own. Holds DOMAIN values.
///
/// | facet | slots | operand | asks about |
/// |---|---|---|---|
/// | IDENTITY | `eq`, `ne`, `in_`, `not_in` | [`LanguageIdOperand`] | the whole tag, all four seats |
/// | LANGUAGE | `language` | [`Language`] | the primary subtag alone |
/// | SCRIPT | `script` | [`ScriptSubtag`], nullable | the script alone, `isNull` included |
/// | REGION | `region` | [`Region`], nullable | the region alone, `isNull` included |
///
/// # *All Chinese* is `{ language: { eq: "zh" } }`, and that is what the component facet is for
///
/// It finds `zh`, `zh-Hans`, `zh-TW` and `zh-Hans-CN` alike, because every one of them stores `zh`
/// in the language column and the predicate reaches that column and no other. The identity facet
/// cannot answer it — `eq: "zh"` is the tag `zh` exactly, with no script and no region — and that
/// is not a defect in either: they are two questions, and a filter that could only ask the first
/// would make the common one unaskable.
///
/// # `script: { isNull: true }` is *no script was declared*
///
/// The one place this filter's null test carries a meaning worth spelling out. A `zh` row has a
/// `NULL` script column and a `zh-Hans` row does not, so the test separates *the file did not say*
/// from *the file said `Hans`* — and, because the composition suppresses a script the language
/// implies, an `en-Latn` row is on the `isNull` side too. That is the same fact from the other end:
/// `en` implies Latin, so declaring it said nothing, so nothing is stored.
///
/// The REGION carries the same test for the same reason, and the ruling names only the script's
/// because that is where the meaning is interesting. Both columns are nullable and both publish
/// `isNull`; the alternative would be a filter whose two optional components behaved differently
/// for no reason a client could read.
///
/// # There is NO `rest` slot, and no ordering over the whole identity
///
/// The tail has no filter word — see [`LanguageId`], where the reason is that a text seat holding
/// three grammars at once has no honest question. It is still reachable: the four identity words
/// carry it, so `eq` over a whole tag constrains the tail exactly.
///
/// The ordering words are absent from the identity facet for the timebase's reason: `de-AT < de-DE`
/// is a fact about spellings, and a filter that published `gt` over a whole tag would invite it to
/// be read as a fact about languages. The COMPONENT facets keep theirs, because a component is one
/// column and its order is the same alphabetical one every text column has.
///
/// **RFC 4647's language RANGES are not here, and that is a deferral rather than a ruling.**
/// `de-*` — a basic range matching `de`, `de-DE` and `de-CH-1901` — is a fifth kind of question,
/// answerable from these columns by a prefix test, and nothing has asked for it. The day something
/// does, it is one more slot.
///
/// # The wire face is DECLARED, not written
///
/// `#[ingraph(composed)]` reads the seven slots below once and emits the registration, the parse and
/// the render from them.
#[derive(Debug, Clone, PartialEq, ingraph::Filter)]
#[ingraph(composed)]
pub struct LanguageIdFilter {
  eq: Option<LanguageId>,
  ne: Option<LanguageId>,
  in_: Option<Box<[LanguageId]>>,
  not_in: Option<Box<[LanguageId]>>,
  language: Option<ScalarFilter<Language, LanguageWire>>,
  script: Option<Nullable<ScalarFilter<ScriptSubtag, ScriptSubtagWire>>>,
  region: Option<Nullable<ScalarFilter<Region, RegionWire>>>,
}

impl LanguageIdFilter {
  /// The empty filter — no operator set on any facet.
  #[inline]
  pub const fn new() -> Self {
    Self {
      eq: None,
      ne: None,
      in_: None,
      not_in: None,
      language: None,
      script: None,
      region: None,
    }
  }

  /// True while NO operator slot is set on ANY facet — so a lowering would emit nothing for this
  /// field.
  ///
  /// Inherent as well as [`GraphqlFilter::is_empty`](crate::GraphqlFilter::is_empty), and the
  /// inherent one wins method resolution: "is anything set" is a property of the FILTER, identical
  /// on every backend, and asking it should not make a caller name one.
  ///
  /// NOT `const`: a nullable component's own emptiness is not a `const fn` in the framework, since
  /// it folds an inner filter's answer together with its null slot.
  pub fn is_empty(&self) -> bool {
    self.eq.is_none()
      && self.ne.is_none()
      && self.in_.is_none()
      && self.not_in.is_none()
      && self.language.as_ref().is_none_or(ScalarFilter::is_empty)
      && self.script.as_ref().is_none_or(Nullable::is_empty)
      && self.region.as_ref().is_none_or(Nullable::is_empty)
  }

  /// The language component's own filter — *all Chinese* lives here.
  #[inline]
  pub const fn language(&self) -> Option<&ScalarFilter<Language, LanguageWire>> {
    self.language.as_ref()
  }

  /// The script component's own filter, with its null test.
  #[inline]
  pub const fn script(&self) -> Option<&Nullable<ScalarFilter<ScriptSubtag, ScriptSubtagWire>>> {
    self.script.as_ref()
  }

  /// The region component's own filter, with its null test.
  #[inline]
  pub const fn region(&self) -> Option<&Nullable<ScalarFilter<Region, RegionWire>>> {
    self.region.as_ref()
  }

  // The four whole-identity operators, READ AND WRITTEN by the framework's own macro. The three
  // component filters above are read by hand because each carries a sentence of its own; these four
  // carry the sentence every operator slot carries, which is the one `opt_accessor!` writes.
  opt_accessor!(eq: LanguageId => with_eq, set_eq, maybe_eq, update_eq);
  opt_accessor!(ne: LanguageId => with_ne, set_ne, maybe_ne, update_ne);
  opt_accessor!(in_: [LanguageId] => with_in_, set_in_, maybe_in_, update_in_);
  opt_accessor!(not_in: [LanguageId] => with_not_in, set_not_in, maybe_not_in, update_not_in);

  /// Replace the language component's filter (consuming).
  #[must_use]
  #[inline]
  pub fn with_language(mut self, language: ScalarFilter<Language, LanguageWire>) -> Self {
    self.set_language(language);
    self
  }

  /// Replace the language component's filter (in place).
  #[inline]
  pub fn set_language(&mut self, language: ScalarFilter<Language, LanguageWire>) -> &mut Self {
    self.language = Some(language);
    self
  }

  /// Replace the script component's filter (consuming).
  #[must_use]
  #[inline]
  pub fn with_script(
    mut self,
    script: Nullable<ScalarFilter<ScriptSubtag, ScriptSubtagWire>>,
  ) -> Self {
    self.set_script(script);
    self
  }

  /// Replace the script component's filter (in place).
  #[inline]
  pub fn set_script(
    &mut self,
    script: Nullable<ScalarFilter<ScriptSubtag, ScriptSubtagWire>>,
  ) -> &mut Self {
    self.script = Some(script);
    self
  }

  /// Replace the region component's filter (consuming).
  #[must_use]
  #[inline]
  pub fn with_region(mut self, region: Nullable<ScalarFilter<Region, RegionWire>>) -> Self {
    self.set_region(region);
    self
  }

  /// Replace the region component's filter (in place).
  #[inline]
  pub fn set_region(&mut self, region: Nullable<ScalarFilter<Region, RegionWire>>) -> &mut Self {
    self.region = Some(region);
    self
  }
}

impl Default for LanguageIdFilter {
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}