ingraph/primitives/lang/id/mod.rs
1//! The [`LanguageId`] composite: the four seats, the composition rules that fill them, the operand
2//! its wire face crosses on, and the filter that guards its four columns.
3
4use core::{fmt, str::FromStr};
5
6use crate::{
7 CompositeFilterMarker, CompositeMarker, DefaultMarker, Nullable, ScalarFilter, ToGraphqlInput,
8};
9use smol_bytes::Utf8Bytes;
10
11use super::{
12 Language, LanguageWire, ParseLanguageError, ParseRegionError, ParseScriptSubtagError, Region,
13 RegionWire, ScriptSubtag, ScriptSubtagWire, registry,
14};
15use crate::graphql::filter::opt_accessor;
16
17#[cfg(feature = "sqlx")]
18mod comparison;
19mod storage;
20
21#[cfg(test)]
22mod tests;
23
24#[cfg(feature = "sqlx")]
25pub use comparison::{LanguageIdCrossingError, SqlLanguageIdComparison};
26pub use storage::LanguageIdColumnError;
27/// Crate-internal: the sub-document reader [`DetectedLanguage`](super::DetectedLanguage)'s own
28/// MongoDB row shares, its four keys being spliced into the SAME top-level document rather than
29/// nested under one of their own — see `detected::storage`'s [`MongoCarrier`](crate::MongoCarrier)
30/// row for why, and its [`MongoExtract`](crate::query::mongo::MongoExtract) row for the read.
31#[cfg(feature = "mongo")]
32pub(crate) use storage::document_seats;
33
34/// A whole language identity — what UTS-35 calls a *unicode language id* and what a track's
35/// metadata actually carries: `de`, `zh-Hans`, `en-US`, `sr-Cyrl-RS`, `en-US-x-lorem`.
36///
37/// FOUR seats, and the fourth is what makes the type lossless:
38///
39/// ```text
40/// language Language always present — a tag with no language is not a tag
41/// script Option<ScriptSubtag> absent where none was declared, or where the language
42/// implies it
43/// region Option<Region> absent where none was declared
44/// rest Option<…> everything past the region, VERBATIM
45/// ```
46///
47/// # The composition rules, and every one of them is the registry's
48///
49/// | sent | held | the rule |
50/// |---|---|---|
51/// | `zh_Hans_CN` | `zh-Hans-CN` | `_` is read as `-`, which is what a filename-safe tag uses |
52/// | `en-Latn` | `en` | `en` implies `Latn`, so declaring it says nothing — `Suppress-Script` |
53/// | `zh-Hans` | `zh-Hans` | `zh` implies NO script, so the declaration is the whole content |
54/// | `i-klingon` | `tlh` | a grandfathered tag, folded by its `Preferred-Value` |
55/// | `GER-latn-de` | `de-DE` | each seat's own door, then the suppression |
56///
57/// **The `Suppress-Script` fold is the one that earns its keep**, and the pair above is why: it
58/// removes a subtag that carries no information (`en-Latn` and `en` are the same identity) and
59/// leaves alone one that carries all of it (`zh-Hans` and `zh-Hant` are two identities). A fold
60/// spelled by hand would have had to decide which languages imply which scripts; this one reads a
61/// column of a vendored file, so the answer is right for all 134 of them and stays right when the
62/// registry moves.
63///
64/// # `rest` is LOSSLESS and has NO filter word, which is one decision rather than two
65///
66/// Everything past the region — variants (`en-US-posix`), extensions (`de-u-co-phonebk`), private
67/// use (`en-x-lorem`) — is held VERBATIM, rendered back verbatim, and counts towards equality. It
68/// is not parsed, not folded, and not case-normalised.
69///
70/// So `en-US-x-Foo` and `en-US-x-foo` are TWO values here, where RFC 5646's own canonical form would
71/// lower-case both. That is the price of the seat being lossless rather than a defect in it: a
72/// private-use sequence's meaning belongs to the private party that wrote it, and this type cannot
73/// know that its case is insignificant. The tail is carried exactly as the file spelled it, and a
74/// caller comparing tails as identifiers gets what the file said.
75///
76/// **The tail has no filter word**, and that follows from the same fact. There is nothing here that
77/// could be asked honestly: `contains` over a text seat holding a mixture of three grammars would
78/// answer questions about spelling rather than about identity, which is the single-text-column game
79/// this type's four columns exist instead of. Asking about a WHOLE identity is what the four
80/// identity words do, and they carry the tail with them.
81///
82/// **The envelope the tail is checked against is deliberately loose**: each of its subtags must be
83/// one to eight ASCII alphanumeric characters, which is the outer shape of every variant, extension
84/// and private-use subtag together. `en-USA` is admitted, though `USA` is not a legal variant,
85/// because a container writes what its muxer believed and a metadata layer's job is to carry it —
86/// the same posture that admits an unregistered language subtag.
87///
88/// # An extlang has no seat, so it rides the tail — and takes the rest of the tag with it
89///
90/// `zh-yue` holds `zh` with a tail of `yue`, because `yue` is three letters and a script is four
91/// while a region is two or three DIGITS. That is the ruled roster doing what it says: the seats are
92/// language, script and region, and BCP 47's extlang position is none of them.
93///
94/// The consequence is worth stating rather than discovering: the tail is a TAIL, so once a subtag
95/// falls into it every later subtag does too. `zh-yue-Hant-HK` holds `zh` with a tail of
96/// `yue-Hant-HK` — the script and region are IN the tail, and no component filter reaches them. The
97/// tag round-trips exactly, and `{ language: { eq: zh } }` still finds it, which is the question the
98/// ruling names. Filtering its script is what is lost, and a `zh-Hant-HK` tag — which is what a
99/// well-formed file writes — has that filterable.
100///
101/// # Equality is the four seats, so it is the CANONICAL identity
102///
103/// `GER-latn-de` and `de-DE` are one value, because each seat folded before it was filled and the
104/// suppression then removed the script. That is what makes a stored row and a query operand meet:
105/// four columns hold the canonical parts, and a query built from any spelling of the same identity
106/// binds the same four.
107///
108/// It is EQUALITY of identities and not of languages, which the same pair says from the other side:
109/// `de` and `de-DE` are two values, because one names a region and the other does not. Asking about
110/// the language they share is the component facet's business, not this one's.
111///
112/// # Ordering is the four seats in order, and it means what a text sort means
113///
114/// [`Ord`] is derived, so it compares the language first, then the script, then the region, then
115/// the tail — each alphabetically, each absent sorting before present. It is a total, stable order
116/// and therefore a usable cursor key, and it is nothing else: `de-AT` sorts before `de-DE` because
117/// `A` sorts before `D`.
118#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
119pub struct LanguageId {
120 language: Language,
121 script: Option<ScriptSubtag>,
122 region: Option<Region>,
123 rest: Option<Utf8Bytes>,
124}
125
126impl LanguageId {
127 /// Read a whole tag, WIDE — any case, `_` or `-`, grandfathered or composed.
128 ///
129 /// The one door in, as each seat's own `new` is for its part.
130 ///
131 /// # The order the rules fire in
132 ///
133 /// 1. **`_` becomes `-`.** A filename-safe tag (`zh_Hans_CN`) is the same tag.
134 /// 2. **The GRANDFATHERED table**, over the whole tag, case-folded. `i-klingon` is `tlh` and
135 /// `zh-guoyu` is `cmn`. Five grandfathered tags name no replacement, and those fall through to
136 /// the ordinary parse — where two of them (`cel-gaulish`, `zh-min`) turn out to be ordinary
137 /// compositions and the three beginning `i-` are refused, a one-letter primary subtag being
138 /// outside the grammar.
139 /// 3. **The SEATS, positionally.** The first subtag is the language. A four-letter subtag next is
140 /// the script; a two-letter or three-digit one after that is the region; everything from the
141 /// first subtag that is neither is the tail.
142 /// 4. **The SUPPRESSION.** A declared script the language already implies is dropped.
143 ///
144 /// # Errors
145 ///
146 /// [`ParseLanguageIdError`], naming the seat that refused and carrying its own error — so a
147 /// client sending `e-US` is told what a language subtag is, by the type that knows.
148 ///
149 /// A seat is only ASKED about a subtag of its own shape, so the shape test and the seat's grammar
150 /// cannot disagree: `zh-Hans-XYZ` never reaches the region door at all, `XYZ` being neither two
151 /// letters nor three digits, and the tail's looser envelope takes it.
152 pub fn new(text: &str) -> Result<Self, ParseLanguageIdError> {
153 if text.is_empty() {
154 return Err(ParseLanguageIdError::Empty);
155 }
156
157 // The separator fold happens FIRST and for the whole tag, so every rule below reads one
158 // spelling. It is the only place this type rewrites its input outside a seat's own door.
159 let normalized;
160 let tag = if text.contains('_') {
161 normalized = text.replace('_', "-");
162 normalized.as_str()
163 } else {
164 text
165 };
166
167 if let Some(preferred) = grandfathered(tag) {
168 // A `Preferred-Value` is always an ordinary composed tag — `tlh`, `cmn`, `en-GB-oxendict` —
169 // so this recurses exactly once and lands in `composed` below.
170 return Self::composed(preferred);
171 }
172
173 Self::composed(tag)
174 }
175
176 /// The three seats and the tail, read positionally out of a normalized tag.
177 fn composed(tag: &str) -> Result<Self, ParseLanguageIdError> {
178 let parts: Vec<&str> = tag.split('-').collect();
179
180 if parts.iter().any(|part| part.is_empty()) {
181 return Err(ParseLanguageIdError::EmptySubtag);
182 }
183
184 let language = Language::new(parts[0]).map_err(ParseLanguageIdError::Language)?;
185 let mut at = 1;
186
187 let script = match parts.get(at) {
188 Some(part) if script_shaped(part) => {
189 at += 1;
190 Some(ScriptSubtag::new(part).map_err(ParseLanguageIdError::ScriptSubtag)?)
191 }
192 _ => None,
193 };
194
195 let region = match parts.get(at) {
196 Some(part) if region_shaped(part) => {
197 at += 1;
198 Some(Region::new(part).map_err(ParseLanguageIdError::Region)?)
199 }
200 _ => None,
201 };
202
203 // The tail is a contiguous SUFFIX of the tag, so it is SLICED rather than rebuilt from the
204 // parts: each consumed subtag cost its own length plus the separator after it, so the sum is
205 // exactly where the tail begins. Slicing is what makes "verbatim" true of the separators too.
206 let consumed: usize = parts[..at].iter().map(|part| part.len() + 1).sum();
207 let rest = match consumed < tag.len() {
208 true => Some(tail(&tag[consumed..])?),
209 false => None,
210 };
211
212 Ok(Self {
213 // The SUPPRESSION, and it is applied here rather than at `ScriptSubtag`'s door because it is
214 // a fact
215 // about the PAIR: a script means nothing beside a language that implies it, and everything
216 // beside one that does not.
217 script: match (&script, language.suppressed_script()) {
218 (Some(declared), Some(implied)) if declared.as_str() == implied => None,
219 _ => script,
220 },
221 language,
222 region,
223 rest,
224 })
225 }
226
227 /// A tag from its four parts, with the suppression applied.
228 ///
229 /// The route a caller building an identity takes, where [`new`](Self::new) is the route a TEXT
230 /// takes. It is total: every part has already been through its own door, and the tail is the one
231 /// seat with nothing to check.
232 ///
233 /// The suppression still fires, which is what keeps the two routes in agreement — a `LanguageId`
234 /// built from `en` and `Latn` is the same value as one parsed from `"en-Latn"`, and both are `en`.
235 #[must_use]
236 pub fn compose(
237 language: Language,
238 script: Option<ScriptSubtag>,
239 region: Option<Region>,
240 rest: Option<Utf8Bytes>,
241 ) -> Self {
242 Self {
243 script: match (&script, language.suppressed_script()) {
244 (Some(declared), Some(implied)) if declared.as_str() == implied => None,
245 _ => script,
246 },
247 language,
248 region,
249 rest,
250 }
251 }
252
253 /// The language, which every identity has.
254 #[inline]
255 #[must_use]
256 pub const fn language(&self) -> &Language {
257 &self.language
258 }
259
260 /// The script, where one was declared and the language does not already imply it.
261 #[inline]
262 #[must_use]
263 pub const fn script(&self) -> Option<&ScriptSubtag> {
264 self.script.as_ref()
265 }
266
267 /// The region, where one was declared.
268 #[inline]
269 #[must_use]
270 pub const fn region(&self) -> Option<&Region> {
271 self.region.as_ref()
272 }
273
274 /// Everything past the region, verbatim — variants, extensions and the private-use sequence.
275 #[inline]
276 #[must_use]
277 pub const fn rest(&self) -> Option<&Utf8Bytes> {
278 self.rest.as_ref()
279 }
280}
281
282/// The widest subtag a tail may hold — the outer envelope of every variant, extension and
283/// private-use subtag BCP 47 defines.
284const TAIL_SUBTAG_MAX: usize = 8;
285
286/// One tail through its envelope, held verbatim.
287///
288/// THE one authority for what a tail may be, read by the tag parser above and by the column decode
289/// next door — so a tail that arrives as the far end of a tag and one that arrives as a column of
290/// its own are admitted by the same rule.
291///
292/// The envelope is deliberately LOOSE: one to eight ASCII alphanumeric characters per subtag, which
293/// is the outer shape of every variant, extension and private-use subtag together rather than any
294/// one of their grammars. See [`LanguageId`], where the reason is the same one that admits an
295/// unregistered language subtag.
296pub(super) fn tail(text: &str) -> Result<Utf8Bytes, ParseLanguageIdError> {
297 for part in text.split('-') {
298 if part.is_empty() {
299 return Err(ParseLanguageIdError::EmptySubtag);
300 }
301 if part.len() > TAIL_SUBTAG_MAX {
302 return Err(ParseLanguageIdError::TailWidth);
303 }
304 if let Some(outside) = part
305 .chars()
306 .find(|character| !character.is_ascii_alphanumeric())
307 {
308 return Err(ParseLanguageIdError::Tail(outside));
309 }
310 }
311
312 Ok(Utf8Bytes::from(text))
313}
314
315/// The widest whole tag the registry grandfathered, in bytes.
316///
317/// Nothing wider can be one, so nothing wider is looked up — which is what lets the case fold for
318/// that lookup use a stack buffer rather than allocating a lower-cased copy of every tag that comes
319/// through the door. `the_grandfathered_table_fits_the_lookup_buffer` is the pin that keeps the
320/// shortcut from silently missing a tag the registry adds.
321const GRANDFATHERED_MAX: usize = 16;
322
323/// The replacement the registry names for a grandfathered tag, or [`None`] for a tag that is not
324/// grandfathered or is grandfathered without one.
325///
326/// The five with no replacement answer [`None`] here and fall through to the ordinary parse, which
327/// is the honest handling: two of them ARE ordinary compositions read subtag by subtag, and the
328/// three beginning `i-` are refused by the language door for a reason it can state.
329fn grandfathered(tag: &str) -> Option<&'static str> {
330 if tag.len() > GRANDFATHERED_MAX {
331 return None;
332 }
333
334 let mut lowered = [0u8; GRANDFATHERED_MAX];
335 for (at, byte) in tag.as_bytes().iter().enumerate() {
336 lowered[at] = byte.to_ascii_lowercase();
337 }
338
339 // SAFETY: `tag` is a `&str` and an ASCII case fold maps each of its bytes to a byte of the same
340 // width and validity — a non-ASCII byte is above `0x7F` and is left alone — so the prefix written
341 // above is the same UTF-8 sequence with some ASCII letters re-cased.
342 let lowered = unsafe { core::str::from_utf8_unchecked(&lowered[..tag.len()]) };
343
344 registry::grandfathered_preferred(lowered)
345}
346
347/// Is this subtag in the SCRIPT position's shape — exactly four ASCII letters?
348fn script_shaped(part: &str) -> bool {
349 part.len() == 4
350 && part
351 .chars()
352 .all(|character| character.is_ascii_alphabetic())
353}
354
355/// Is this subtag in the REGION position's shape — two ASCII letters, or three ASCII digits?
356fn region_shaped(part: &str) -> bool {
357 let letters = part.len() == 2
358 && part
359 .chars()
360 .all(|character| character.is_ascii_alphabetic());
361 let digits = part.len() == 3 && part.chars().all(|character| character.is_ascii_digit());
362
363 letters || digits
364}
365
366/// The canonical spelling: the seats that are filled, in order, joined by `-`.
367///
368/// The inverse of [`FromStr`] over canonical text, which is what makes it usable as a cursor and as
369/// the `tag` field a client reads back into a filter operand.
370impl fmt::Display for LanguageId {
371 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
372 f.write_str(self.language.as_str())?;
373
374 if let Some(script) = &self.script {
375 write!(f, "-{script}")?;
376 }
377 if let Some(region) = &self.region {
378 write!(f, "-{region}")?;
379 }
380 if let Some(rest) = &self.rest {
381 write!(f, "-{}", rest.as_str())?;
382 }
383
384 Ok(())
385 }
386}
387
388/// The canonical tag, in quotes — not the four seats, which would make an assertion message four
389/// times longer than the value it is about.
390impl fmt::Debug for LanguageId {
391 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
392 write!(f, "LanguageId({:?})", self.to_string())
393 }
394}
395
396impl FromStr for LanguageId {
397 type Err = ParseLanguageIdError;
398
399 #[inline]
400 fn from_str(text: &str) -> Result<Self, Self::Err> {
401 Self::new(text)
402 }
403}
404
405/// A tag with no other seats filled — the shape a bare language subtag composes to.
406impl From<Language> for LanguageId {
407 #[inline]
408 fn from(language: Language) -> Self {
409 Self {
410 language,
411 script: None,
412 region: None,
413 rest: None,
414 }
415 }
416}
417
418/// A string does not name a language identity.
419///
420/// The three seat variants CARRY the seat's own error rather than restating it, which is what keeps
421/// one grammar per subtag kind: a client sending `zh-Hans-XYZ` is told that a region written in
422/// letters is exactly two, by [`Region`]'s own words.
423#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
424pub enum ParseLanguageIdError {
425 /// Nothing was sent — an ABSENT identity rather than a malformed one, whose home is a `NULL`
426 /// column.
427 Empty,
428 /// A subtag between two separators is empty: `en--US`, or a tag with a trailing `-`.
429 EmptySubtag,
430 /// The first subtag is not a language. This is where `i-default` and `i-mingo` land — a
431 /// one-letter primary subtag is outside the grammar, and those two are grandfathered tags the
432 /// registry names no replacement for.
433 Language(ParseLanguageError),
434 /// A subtag in the script position is four letters and still not a script. Unreachable today, the
435 /// position test being the same width and alphabet the script door checks; it is propagated
436 /// rather than unwrapped so that a widened position test cannot become a panic.
437 ScriptSubtag(ParseScriptSubtagError),
438 /// A subtag in the region position is not a region, for the same reason and with the same
439 /// posture.
440 Region(ParseRegionError),
441 /// A tail subtag holds a character that is neither an ASCII letter nor an ASCII digit, carrying
442 /// the first one found.
443 Tail(char),
444 /// A tail subtag is more than eight characters, which no variant, extension or private-use
445 /// subtag is.
446 TailWidth,
447}
448
449impl fmt::Display for ParseLanguageIdError {
450 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
451 match self {
452 Self::Empty => {
453 f.write_str("a language tag opens with a language subtag, and nothing was sent")
454 }
455 Self::EmptySubtag => f.write_str("a language tag has no empty subtag between its separators"),
456 Self::Language(refused) => write!(f, "the tag's language subtag is not one: {refused}"),
457 Self::ScriptSubtag(refused) => write!(f, "the tag's script subtag is not one: {refused}"),
458 Self::Region(refused) => write!(f, "the tag's region subtag is not one: {refused}"),
459 Self::Tail(outside) => write!(
460 f,
461 "a variant, extension or private-use subtag is letters and digits, so `{outside}` is not \
462 one of its characters"
463 ),
464 Self::TailWidth => {
465 f.write_str("a variant, extension or private-use subtag is at most eight characters")
466 }
467 }
468 }
469}
470
471impl core::error::Error for ParseLanguageIdError {
472 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
473 match self {
474 Self::Language(refused) => Some(refused),
475 Self::ScriptSubtag(refused) => Some(refused),
476 Self::Region(refused) => Some(refused),
477 Self::Empty | Self::EmptySubtag | Self::Tail(_) | Self::TailWidth => None,
478 }
479 }
480}
481
482/// A whole identity, on its way IN — the carrier the identity axis's four operators cross on.
483///
484/// A type of its own rather than [`LanguageId`] itself, and GraphQL's own namespace is what forces
485/// it: objects and input types share one, so the scalar a client SENDS cannot be spelled
486/// `LanguageId` while an object of that name is published. Every operand newtype in a declaring
487/// crate states the same argument for the same reason.
488///
489/// Transparent in both directions: it holds a [`LanguageId`] that has already been validated, so
490/// [`ToGraphqlInput`]'s crossing off it is [`Infallible`](core::convert::Infallible). Every refusal
491/// happens at the scalar's own `parse`, which is the one door a wire value comes through.
492#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
493pub struct LanguageIdOperand(LanguageId);
494
495impl LanguageIdOperand {
496 /// Wrap an identity as an operand.
497 #[inline]
498 #[must_use]
499 pub const fn new(id: LanguageId) -> Self {
500 Self(id)
501 }
502
503 /// The wrapped identity.
504 #[inline]
505 #[must_use]
506 pub fn get(&self) -> &LanguageId {
507 &self.0
508 }
509}
510
511impl From<LanguageId> for LanguageIdOperand {
512 #[inline]
513 fn from(id: LanguageId) -> Self {
514 Self(id)
515 }
516}
517
518impl From<LanguageIdOperand> for LanguageId {
519 #[inline]
520 fn from(operand: LanguageIdOperand) -> Self {
521 operand.0
522 }
523}
524
525impl ToGraphqlInput for LanguageId {
526 type Input = LanguageIdOperand;
527 type Error = core::convert::Infallible;
528
529 #[inline]
530 fn cross(input: Self::Input) -> Result<Self, Self::Error> {
531 Ok(input.into())
532 }
533
534 #[inline]
535 fn carry(operand: &Self) -> Self::Input {
536 LanguageIdOperand::new(operand.clone())
537 }
538}
539
540/// **The crossing OUT, and it is NOT the operand's type** — which is the whole asymmetry the two
541/// namespaces force.
542///
543/// A client SENDS a `LanguageIdOperand`, which is a scalar holding the canonical tag, and RECEIVES a
544/// `LanguageId`, which is the `#[Object]` published next door: five fields, the four seats plus the
545/// rendering that spells them. So this row hands back a BORROW of the value the row holds and lets
546/// that object resolve it, where [`ToGraphqlInput`] above has to wrap.
547///
548/// The pair is what makes the identity a round trip rather than half of one: the object's `tag` field
549/// is the operand's own text, so a client reads a tag out of one and writes it back into the other.
550///
551/// Without this row a declaration storing a `LanguageId` could publish NOTHING — an emitted face
552/// returns `<LanguageId as ToGraphqlOutput>::Output<'_>`, so the absence is `E0277` at the face and
553/// not at the column.
554impl crate::ToGraphqlOutput for LanguageId {
555 type Output<'a> = &'a Self;
556
557 #[inline]
558 fn to_graphql_output(marked: &Self) -> &Self {
559 marked
560 }
561}
562
563/// What guards a [`LanguageId`] column — [`Language`]'s row, and the same reading of it: an
564/// identity stores every field it declares, so the two seats name one predicate.
565///
566/// [`Language`]: super::Language
567impl CompositeFilterMarker for LanguageId {
568 type Filter = LanguageIdFilter;
569 type ColumnFilter = LanguageIdFilter;
570}
571
572/// The interpretation a [`LanguageId`] field is read under — [`Language`]'s reading, and this crate
573/// no longer mints either: an identity occupies four columns OF ITS OWN, so all four can be absent
574/// together, which is exactly the VALUE family [`CompositeMarker`] names — a track nobody tagged is
575/// not a track tagged `und`.
576///
577/// [`Language`]: super::Language
578impl DefaultMarker for LanguageId {
579 type Marker = CompositeMarker<LanguageId>;
580}
581
582/// The filter that guards a [`LanguageId`] column: the whole IDENTITY, and each COMPONENT that has
583/// a column of its own. Holds DOMAIN values.
584///
585/// | facet | slots | operand | asks about |
586/// |---|---|---|---|
587/// | IDENTITY | `eq`, `ne`, `in_`, `not_in` | [`LanguageIdOperand`] | the whole tag, all four seats |
588/// | LANGUAGE | `language` | [`Language`] | the primary subtag alone |
589/// | SCRIPT | `script` | [`ScriptSubtag`], nullable | the script alone, `isNull` included |
590/// | REGION | `region` | [`Region`], nullable | the region alone, `isNull` included |
591///
592/// # *All Chinese* is `{ language: { eq: "zh" } }`, and that is what the component facet is for
593///
594/// It finds `zh`, `zh-Hans`, `zh-TW` and `zh-Hans-CN` alike, because every one of them stores `zh`
595/// in the language column and the predicate reaches that column and no other. The identity facet
596/// cannot answer it — `eq: "zh"` is the tag `zh` exactly, with no script and no region — and that
597/// is not a defect in either: they are two questions, and a filter that could only ask the first
598/// would make the common one unaskable.
599///
600/// # `script: { isNull: true }` is *no script was declared*
601///
602/// The one place this filter's null test carries a meaning worth spelling out. A `zh` row has a
603/// `NULL` script column and a `zh-Hans` row does not, so the test separates *the file did not say*
604/// from *the file said `Hans`* — and, because the composition suppresses a script the language
605/// implies, an `en-Latn` row is on the `isNull` side too. That is the same fact from the other end:
606/// `en` implies Latin, so declaring it said nothing, so nothing is stored.
607///
608/// The REGION carries the same test for the same reason, and the ruling names only the script's
609/// because that is where the meaning is interesting. Both columns are nullable and both publish
610/// `isNull`; the alternative would be a filter whose two optional components behaved differently
611/// for no reason a client could read.
612///
613/// # There is NO `rest` slot, and no ordering over the whole identity
614///
615/// The tail has no filter word — see [`LanguageId`], where the reason is that a text seat holding
616/// three grammars at once has no honest question. It is still reachable: the four identity words
617/// carry it, so `eq` over a whole tag constrains the tail exactly.
618///
619/// The ordering words are absent from the identity facet for the timebase's reason: `de-AT < de-DE`
620/// is a fact about spellings, and a filter that published `gt` over a whole tag would invite it to
621/// be read as a fact about languages. The COMPONENT facets keep theirs, because a component is one
622/// column and its order is the same alphabetical one every text column has.
623///
624/// **RFC 4647's language RANGES are not here, and that is a deferral rather than a ruling.**
625/// `de-*` — a basic range matching `de`, `de-DE` and `de-CH-1901` — is a fifth kind of question,
626/// answerable from these columns by a prefix test, and nothing has asked for it. The day something
627/// does, it is one more slot.
628///
629/// # The wire face is DECLARED, not written
630///
631/// `#[ingraph(composed)]` reads the seven slots below once and emits the registration, the parse and
632/// the render from them.
633#[derive(Debug, Clone, PartialEq, ingraph::Filter)]
634#[ingraph(composed)]
635pub struct LanguageIdFilter {
636 eq: Option<LanguageId>,
637 ne: Option<LanguageId>,
638 in_: Option<Box<[LanguageId]>>,
639 not_in: Option<Box<[LanguageId]>>,
640 language: Option<ScalarFilter<Language, LanguageWire>>,
641 script: Option<Nullable<ScalarFilter<ScriptSubtag, ScriptSubtagWire>>>,
642 region: Option<Nullable<ScalarFilter<Region, RegionWire>>>,
643}
644
645impl LanguageIdFilter {
646 /// The empty filter — no operator set on any facet.
647 #[inline]
648 pub const fn new() -> Self {
649 Self {
650 eq: None,
651 ne: None,
652 in_: None,
653 not_in: None,
654 language: None,
655 script: None,
656 region: None,
657 }
658 }
659
660 /// True while NO operator slot is set on ANY facet — so a lowering would emit nothing for this
661 /// field.
662 ///
663 /// Inherent as well as [`GraphqlFilter::is_empty`](crate::GraphqlFilter::is_empty), and the
664 /// inherent one wins method resolution: "is anything set" is a property of the FILTER, identical
665 /// on every backend, and asking it should not make a caller name one.
666 ///
667 /// NOT `const`: a nullable component's own emptiness is not a `const fn` in the framework, since
668 /// it folds an inner filter's answer together with its null slot.
669 pub fn is_empty(&self) -> bool {
670 self.eq.is_none()
671 && self.ne.is_none()
672 && self.in_.is_none()
673 && self.not_in.is_none()
674 && self.language.as_ref().is_none_or(ScalarFilter::is_empty)
675 && self.script.as_ref().is_none_or(Nullable::is_empty)
676 && self.region.as_ref().is_none_or(Nullable::is_empty)
677 }
678
679 /// The language component's own filter — *all Chinese* lives here.
680 #[inline]
681 pub const fn language(&self) -> Option<&ScalarFilter<Language, LanguageWire>> {
682 self.language.as_ref()
683 }
684
685 /// The script component's own filter, with its null test.
686 #[inline]
687 pub const fn script(&self) -> Option<&Nullable<ScalarFilter<ScriptSubtag, ScriptSubtagWire>>> {
688 self.script.as_ref()
689 }
690
691 /// The region component's own filter, with its null test.
692 #[inline]
693 pub const fn region(&self) -> Option<&Nullable<ScalarFilter<Region, RegionWire>>> {
694 self.region.as_ref()
695 }
696
697 // The four whole-identity operators, READ AND WRITTEN by the framework's own macro. The three
698 // component filters above are read by hand because each carries a sentence of its own; these four
699 // carry the sentence every operator slot carries, which is the one `opt_accessor!` writes.
700 opt_accessor!(eq: LanguageId => with_eq, set_eq, maybe_eq, update_eq);
701 opt_accessor!(ne: LanguageId => with_ne, set_ne, maybe_ne, update_ne);
702 opt_accessor!(in_: [LanguageId] => with_in_, set_in_, maybe_in_, update_in_);
703 opt_accessor!(not_in: [LanguageId] => with_not_in, set_not_in, maybe_not_in, update_not_in);
704
705 /// Replace the language component's filter (consuming).
706 #[must_use]
707 #[inline]
708 pub fn with_language(mut self, language: ScalarFilter<Language, LanguageWire>) -> Self {
709 self.set_language(language);
710 self
711 }
712
713 /// Replace the language component's filter (in place).
714 #[inline]
715 pub fn set_language(&mut self, language: ScalarFilter<Language, LanguageWire>) -> &mut Self {
716 self.language = Some(language);
717 self
718 }
719
720 /// Replace the script component's filter (consuming).
721 #[must_use]
722 #[inline]
723 pub fn with_script(
724 mut self,
725 script: Nullable<ScalarFilter<ScriptSubtag, ScriptSubtagWire>>,
726 ) -> Self {
727 self.set_script(script);
728 self
729 }
730
731 /// Replace the script component's filter (in place).
732 #[inline]
733 pub fn set_script(
734 &mut self,
735 script: Nullable<ScalarFilter<ScriptSubtag, ScriptSubtagWire>>,
736 ) -> &mut Self {
737 self.script = Some(script);
738 self
739 }
740
741 /// Replace the region component's filter (consuming).
742 #[must_use]
743 #[inline]
744 pub fn with_region(mut self, region: Nullable<ScalarFilter<Region, RegionWire>>) -> Self {
745 self.set_region(region);
746 self
747 }
748
749 /// Replace the region component's filter (in place).
750 #[inline]
751 pub fn set_region(&mut self, region: Nullable<ScalarFilter<Region, RegionWire>>) -> &mut Self {
752 self.region = Some(region);
753 self
754 }
755}
756
757impl Default for LanguageIdFilter {
758 #[inline]
759 fn default() -> Self {
760 Self::new()
761 }
762}