Debian Codegraph @

debian/rust-vendor/icu_datetime/src/provider/skeleton/helpers.rs

raw
1 // This file is part of ICU4X. For terms of use, please see the file
2 // called LICENSE at the top level of the ICU4X source tree
3 // (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5 use alloc::collections::BTreeMap;
6 use alloc::vec;
7 use alloc::vec::Vec;
8 use core::cmp::Ordering;
9 use icu_plurals::PluralElements;
10
11 use crate::{
12 options::SubsecondDigits,
13 provider::{
14 fields::{self, Field, FieldLength, FieldSymbol, components},
15 pattern::{PatternItem, TimeGranularity, naively_apply_hour_cycle, runtime},
16 skeleton::{FullLongMediumShort, GenericLengthPatterns, reference},
17 },
18 };
19
20 // The following scalar values are for testing the suitability of a skeleton's field for the
21 // given input. Per UTS 35, the better the fit of a pattern, the "lower the distance". In this
22 // implementation each distance type is separated by an order of magnitiude. This magnitude needs
23 // to be at minimum a multiple of the max length of fields. As of CLDR 38 (2021-01), the max length
24 // of a skeleton in the "availableFormats" contained a total of 4 fields. The scores use a multiple
25 // of 10, as a number that will contain the range, and be easy to reason with.
26 //
27 // The only exception is on the largest magnitude of values (MISSING_OR_SKELETON_EXTRA_SYMBOL). The
28 // missing or extra count BOTH the requested fields and skeleton fields. This is fine since there
29 // is no higher magnitude.
30
31 const MAX_SKELETON_FIELDS: u32 = 10;
32
33 // Per the skeleton matching algorithm:
34 // https://unicode.org/reports/tr35/tr35-dates.html#Matching_Skeletons
35
36 // > 1. "Input skeleton symbols" are replaced with the best match for a given locale.
37 // > - Hour: j → {H, k, h, K} + {a, b, B}
38 // > J → {H, k, h, K}
39 // > C → j + day period
40
41 // The components::Bag does not support step 1
42
43 // > 2. For fields with symbols representing the same type (year, month, day, etc):
44 // > A. Most symbols have a small distance from each other.
45 // > - Months: M ≅ L (9 ≅ 9) conjunction, vs stand-alone
46 // > Week: E ≅ c (Tue ≅ 2)
47 // > Period: a ≅ b ≅ B (am. ≅ mid. ≅ at night)
48 // > Hour: H ≅ k ≅ h ≅ K (23, 24, 12, 11)
49
50 // For step 2, the components::Bag will not produce "stand-alone" months, as no skeletons
51 // contain stand-alone months.
52
53 const NO_DISTANCE: u32 = 0;
54
55 // B. Width differences among fields, other than those marking text vs numeric, are given small
56 // distance from each other.
57 // - MMM ≅ MMMM (Sep ≅ September)
58 // MM ≅ M (09 ≅ 9)
59 const WIDTH_MISMATCH_DISTANCE: u32 = 1;
60
61 // If a glue pattern is required, give a small penalty.
62 const GLUE_DISTANCE: u32 = 10;
63
64 // C. Numeric and text fields are given a larger distance from each other.
65 // - MMM ≈ MM (Sep ≈ 09)
66 // MMM
67 const TEXT_VS_NUMERIC_DISTANCE: u32 = 100;
68
69 // D. Symbols representing substantial differences (week of year vs week of month) are given much
70 // larger a distances from each other.
71 // - d ≋ D; (12 ≋ 345) Day of month vs Day of year
72 const SUBSTANTIAL_DIFFERENCES_DISTANCE: u32 = 1000;
73
74 // A skeleton had more symbols than what was requested.
75 const SKELETON_EXTRA_SYMBOL: u32 = 10000;
76
77 // A requested symbol is missing in the skeleton. Note that this final value can be more than
78 // MAX_SKELETON_FIELDS, as it's counting the missing requested fields, which can be longer than
79 // the stored skeletons. There cannot be any cases higher than this one.
80 const REQUESTED_SYMBOL_MISSING: u32 = 100000;
81
82 /// The best skeleton found, alongside information on how well it matches.
83 ///
84 /// According to the [UTS 35 skeleton matching algorithm](https://unicode.org/reports/tr35/tr35-dates.html#Matching_Skeletons)
85 /// there will be a guaranteed match for a skeleton. However, with this initial implementation,
86 /// there is no attempt to add on missing fields. This enum encodes the variants for the current
87 /// search for a best skeleton.
88 ///
89 /// The patterns are paired with a measure of their quality.
90 ///
91 /// <div class="stab unstable">
92 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
93 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
94 /// to be stable, their Rust representation might not be. Use with caution.
95 /// </div>
96 #[derive(Debug, PartialEq, Clone)]
97 #[allow(missing_docs)]
98 pub enum BestSkeleton<T> {
99 AllFieldsMatch(T, SkeletonQuality),
100 MissingOrExtraFields(T, SkeletonQuality),
101 NoMatch,
102 }
103
104 /// A measure of the quality of a skeleton.
105 ///
106 /// Internally, this is a u32, a "distance" value. This value is highly
107 /// unstable and should not be compared across versions. It should be used
108 /// only for comparing against other distances in the same version of ICU4X.
109 ///
110 /// <div class="stab unstable">
111 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
112 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
113 /// to be stable, their Rust representation might not be. Use with caution.
114 /// </div>
115 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
116 pub struct SkeletonQuality(u32);
117
118 impl SkeletonQuality {
119 /// Returns the worst possible quality measure.
120 pub fn worst() -> SkeletonQuality {
121 SkeletonQuality(u32::MAX)
122 }
123 /// Returns the best possible quality measure.
124 pub fn best() -> SkeletonQuality {
125 SkeletonQuality(0)
126 }
127 /// Returns whether this is an "excellent" match by an arbitrary definition.
128 pub fn is_excellent_match(self) -> bool {
129 self.0 < GLUE_DISTANCE
130 }
131 }
132
133 /// This function swaps out the time zone name field for the appropriate one. Skeleton matching
134 /// only needs to find a single "v" field, and then the time zone name can expand from there.
135 ///
136 /// <div class="stab unstable">
137 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
138 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
139 /// to be stable, their Rust representation might not be. Use with caution.
140 /// </div>
141 fn naively_apply_time_zone_name(
142 pattern: &mut runtime::Pattern,
143 time_zone_name: Option<components::TimeZoneName>,
144 ) {
145 // If there is a preference overriding the hour cycle, apply it now.
146 if let Some(time_zone_name) = time_zone_name {
147 runtime::helpers::maybe_replace_first(pattern, |item| {
148 if let PatternItem::Field(Field {
149 symbol: FieldSymbol::TimeZone(_),
150 length: _,
151 }) = item
152 {
153 Some(PatternItem::Field((time_zone_name).into()))
154 } else {
155 None
156 }
157 });
158 }
159 }
160
161 // Note: This could return a Cow<'a, Pattern>, but it affects every other part of the API to
162 // add a lifetime here. The pattern returned here could be one that we've already constructed in
163 // the CLDR as an exotic type, or it could be one that was modified to meet the requirements of
164 // the components bag.
165
166 /// Given a set of fields (which represents a skeleton), try to create a best localized pattern
167 // for those fields.
168 ///
169 /// * `skeletons` - The skeletons that will be matched against
170 /// * `length_patterns` - Contains information on how to combine date and time patterns.
171 /// * `fields` - The desired fields to match against.
172 /// * `prefer_matched_pattern` - This algorithm does some extra steps of trying to respect
173 /// the desired fields, even if the provider data doesn't completely match. This
174 /// configuration option makes it so that the final pattern won't have additional work
175 /// done to mutate it to match the fields. It will prefer the actual matched pattern.
176 ///
177 /// <div class="stab unstable">
178 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
179 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
180 /// to be stable, their Rust representation might not be. Use with caution.
181 /// </div>
182 pub fn create_best_pattern_for_fields<'data>(
183 skeletons: &BTreeMap<reference::Skeleton, PluralElements<runtime::Pattern<'data>>>,
184 length_patterns: &GenericLengthPatterns<'data>,
185 fields: &[Field],
186 components: &components::Bag,
187 prefer_matched_pattern: bool,
188 ) -> BestSkeleton<PluralElements<runtime::Pattern<'data>>> {
189 let first_pattern_match =
190 get_best_available_format_pattern(skeletons, fields, prefer_matched_pattern);
191
192 // Try to match a skeleton to all of the fields.
193 if let BestSkeleton::AllFieldsMatch(mut pattern, d) = first_pattern_match {
194 pattern.for_each_mut(|pattern| {
195 naively_apply_hour_cycle(pattern, components.hour_cycle);
196 naively_apply_time_zone_name(pattern, components.time_zone_name);
197 apply_subseconds(pattern, components.subsecond);
198 });
199 return BestSkeleton::AllFieldsMatch(pattern, d);
200 }
201
202 let FieldsByType { date, time } = group_fields_by_type(fields);
203
204 if date.is_empty() || time.is_empty() {
205 return match first_pattern_match {
206 BestSkeleton::AllFieldsMatch(_, _) => {
207 unreachable!("Logic error in implementation. AllFieldsMatch handled above.")
208 }
209 BestSkeleton::MissingOrExtraFields(mut pattern, d) => {
210 if date.is_empty() {
211 pattern.for_each_mut(|pattern| {
212 naively_apply_hour_cycle(pattern, components.hour_cycle);
213 naively_apply_time_zone_name(pattern, components.time_zone_name);
214 apply_subseconds(pattern, components.subsecond);
215 });
216 }
217 BestSkeleton::MissingOrExtraFields(pattern, d)
218 }
219 BestSkeleton::NoMatch => BestSkeleton::NoMatch,
220 };
221 }
222
223 // Match the date and time, and then simplify the combinatorial logic of the results into
224 // an optional values of the results, and a boolean value.
225 let (date_patterns, date_missing_or_extra, date_distance) =
226 match get_best_available_format_pattern(skeletons, &date, prefer_matched_pattern) {
227 BestSkeleton::MissingOrExtraFields(fields, d) => (Some(fields), true, d),
228 BestSkeleton::AllFieldsMatch(fields, d) => (Some(fields), false, d),
229 BestSkeleton::NoMatch => (None, true, SkeletonQuality(REQUESTED_SYMBOL_MISSING)),
230 };
231
232 let (time_patterns, time_missing_or_extra, time_distance) =
233 match get_best_available_format_pattern(skeletons, &time, prefer_matched_pattern) {
234 BestSkeleton::MissingOrExtraFields(fields, d) => (Some(fields), true, d),
235 BestSkeleton::AllFieldsMatch(fields, d) => (Some(fields), false, d),
236 BestSkeleton::NoMatch => (None, true, SkeletonQuality(REQUESTED_SYMBOL_MISSING)),
237 };
238 let time_pattern: Option<runtime::Pattern<'data>> = time_patterns.map(|pattern| {
239 #[allow(clippy::unwrap_used)] // only date patterns can contain plural variants
240 let mut pattern = pattern.try_into_other().unwrap();
241 naively_apply_hour_cycle(&mut pattern, components.hour_cycle);
242 naively_apply_time_zone_name(&mut pattern, components.time_zone_name);
243 apply_subseconds(&mut pattern, components.subsecond);
244 pattern
245 });
246
247 // Determine how to combine the date and time.
248 let patterns = match (date_patterns, time_pattern) {
249 (Some(mut date_patterns), Some(time_pattern)) => {
250 let month_field = fields
251 .iter()
252 .find(|f| matches!(f.symbol, FieldSymbol::Month(_)));
253
254 // Per UTS-35, choose a "length" pattern for combining the date and time.
255 // https://unicode.org/reports/tr35/tr35-dates.html#Matching_Skeletons
256 //
257 // 1. If the requested date fields include Wide month and weekday name of any length, use length::Date::Full
258 // 2. Otherwise, if the requested date fields include wide month, use length::Date::Long
259 // 3. Otherwise, if the requested date fields include abbreviated month, use length::Date::Medium
260 // 4. Otherwise use length::Date::Short
261 let length = match month_field {
262 Some(field) => match field.length {
263 FieldLength::Four => {
264 let weekday = fields
265 .iter()
266 .find(|f| matches!(f.symbol, FieldSymbol::Weekday(_)));
267
268 if weekday.is_some() {
269 FullLongMediumShort::Full
270 } else {
271 FullLongMediumShort::Long
272 }
273 }
274 FieldLength::Three => FullLongMediumShort::Medium,
275 _ => FullLongMediumShort::Short,
276 },
277 None => FullLongMediumShort::Short,
278 };
279
280 use crate::provider::pattern::runtime::GenericPattern;
281 let dt_pattern: &GenericPattern<'data> = match length {
282 FullLongMediumShort::Full => &length_patterns.full,
283 FullLongMediumShort::Long => &length_patterns.long,
284 FullLongMediumShort::Medium => &length_patterns.medium,
285 FullLongMediumShort::Short => &length_patterns.short,
286 };
287
288 date_patterns.for_each_mut(|pattern| {
289 let date = pattern.clone();
290 let time = time_pattern.clone();
291
292 // TODO(#2626) - Since this is fallible, we should make this method fallible.
293 #[expect(clippy::expect_used)] // Generic pattern combination should never fail.
294 let dt = dt_pattern
295 .clone()
296 .combined(date, time)
297 .expect("Failed to combine date and time");
298 *pattern = dt;
299 });
300 Some(date_patterns)
301 }
302 (None, Some(pattern)) => Some(PluralElements::new(pattern)),
303 (Some(patterns), None) => Some(patterns),
304 (None, None) => None,
305 };
306
307 let distance = SkeletonQuality(
308 date_distance
309 .0
310 .saturating_add(time_distance.0)
311 .saturating_add(GLUE_DISTANCE),
312 );
313 match patterns {
314 Some(patterns) => {
315 if date_missing_or_extra || time_missing_or_extra {
316 BestSkeleton::MissingOrExtraFields(patterns, distance)
317 } else {
318 BestSkeleton::AllFieldsMatch(patterns, distance)
319 }
320 }
321 None => BestSkeleton::NoMatch,
322 }
323 }
324
325 struct FieldsByType {
326 pub date: Vec<Field>,
327 pub time: Vec<Field>,
328 }
329
330 fn group_fields_by_type(fields: &[Field]) -> FieldsByType {
331 let mut date = Vec::new();
332 let mut time = Vec::new();
333
334 for field in fields {
335 match field.symbol {
336 // Date components:
337 // Note: Weekdays are included in both time and date skeletons.
338 // - Time examples: "EBhm" "EBhms" "Ed" "Ehm" "EHm" "Ehms" "EHms"
339 // - Date examples: "GyMMMEd" "MEd" "MMMEd" "MMMMEd" "yMEd" "yMMMEd"
340 // - Solo example: "E"
341 FieldSymbol::Era
342 | FieldSymbol::Year(_)
343 | FieldSymbol::Month(_)
344 | FieldSymbol::Week(_)
345 | FieldSymbol::Day(_)
346 | FieldSymbol::Weekday(_) => date.push(*field),
347
348 // Time components:
349 FieldSymbol::DayPeriod(_)
350 | FieldSymbol::Hour(_)
351 | FieldSymbol::Minute
352 | FieldSymbol::Second(_)
353 | FieldSymbol::TimeZone(_)
354 | FieldSymbol::DecimalSecond(_) => time.push(*field),
355 // Other components
356 // TODO(#486)
357 // FieldSymbol::Era(_) => other.push(*field),
358 // Plus others...
359 };
360 }
361
362 FieldsByType { date, time }
363 }
364
365 /// Alters given Pattern so that its fields have the same length as 'fields'.
366 ///
367 /// For example the "d MMM y" pattern will be changed to "d MMMM y" given fields ["y", "MMMM", "d"].
368 fn adjust_pattern_field_lengths(fields: &[Field], pattern: &mut runtime::Pattern) {
369 runtime::helpers::maybe_replace(pattern, |item| {
370 if let PatternItem::Field(pattern_field) = item
371 && let Some(requested_field) = fields
372 .iter()
373 .find(|field| field.symbol.skeleton_cmp(pattern_field.symbol).is_eq())
374 && requested_field.length != pattern_field.length
375 && requested_field.get_length_type() == pattern_field.get_length_type()
376 {
377 let length = requested_field.length;
378 let length = if requested_field.symbol.is_at_least_abbreviated() {
379 length.numeric_to_abbr()
380 } else {
381 length
382 };
383 return Some(PatternItem::Field(Field {
384 length,
385 ..*pattern_field
386 }));
387 }
388 None
389 })
390 }
391
392 /// Alters given Pattern so that it will have a fractional second field if it was requested.
393 ///
394 /// If the requested skeleton included both seconds and fractional seconds and the dateFormatItem
395 /// skeleton included seconds but not fractional seconds, then the seconds field of the corresponding
396 /// pattern should be adjusted by appending the locale’s decimal separator, followed by the sequence
397 /// of ‘S’ characters from the requested skeleton.
398 /// (see <https://unicode.org/reports/tr35/tr35-dates.html#Matching_Skeletons>)
399 fn apply_subseconds(pattern: &mut runtime::Pattern, subseconds: Option<SubsecondDigits>) {
400 if let Some(subseconds) = subseconds {
401 let mut items = pattern.items.to_vec();
402 for item in items.iter_mut() {
403 if let PatternItem::Field(
404 field @ Field {
405 symbol:
406 FieldSymbol::Second(fields::Second::Second) | FieldSymbol::DecimalSecond(_),
407 ..
408 },
409 ) = item
410 {
411 field.symbol = FieldSymbol::from_subsecond_digits(subseconds);
412 };
413 }
414 *pattern = runtime::Pattern::from(items);
415 pattern
416 .metadata
417 .set_time_granularity(TimeGranularity::Nanoseconds);
418 }
419 }
420
421 /// A match result returned by [`find_best_skeleton`].
422 ///
423 /// <div class="stab unstable">
424 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
425 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
426 /// to be stable, their Rust representation might not be. Use with caution.
427 /// </div>
428 #[derive(Debug, Clone, Copy)]
429 pub struct SkeletonMatch<'a, T> {
430 /// The skeleton that was matched.
431 pub skeleton: &'a reference::Skeleton,
432 /// The value mapped to this skeleton (e.g., a pattern).
433 pub value: &'a T,
434 /// The match distance score. Lower is better. A distance of 0 is an exact match.
435 pub distance: u32,
436 /// The number of requested fields that were not present in the matched skeleton.
437 pub missing_fields: usize,
438 }
439
440 /// Finds the best matching skeleton from a map of skeletons.
441 ///
442 /// This performs the matching phase of the UTS 35 skeleton matching algorithm.
443 ///
444 /// <div class="stab unstable">
445 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
446 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
447 /// to be stable, their Rust representation might not be. Use with caution.
448 /// </div>
449 pub fn find_best_skeleton<'a, T>(
450 skeletons: &'a BTreeMap<reference::Skeleton, T>,
451 fields: &[Field],
452 ) -> Option<SkeletonMatch<'a, T>> {
453 let mut closest_match = None;
454 let mut closest_distance: u32 = u32::MAX;
455
456 for (skeleton, value) in skeletons.iter() {
457 debug_assert!(
458 skeleton.fields_len() <= MAX_SKELETON_FIELDS as usize,
459 "The distance mechanism assumes skeletons are less than MAX_SKELETON_FIELDS in length."
460 );
461 let mut missing_fields = 0;
462 let mut distance: u32 = 0;
463 // The distance should fit into a u32.
464
465 let mut requested_fields = fields.iter().peekable();
466 let mut skeleton_fields = skeleton.fields_iter().peekable();
467
468 loop {
469 let next = (requested_fields.peek(), skeleton_fields.peek());
470
471 // Try to find matching symbols.
472 match next {
473 (Some(requested_field), Some(skeleton_field)) => {
474 debug_assert!(
475 // As of the time of this writing, stand-alone months are not in the CLDR
476 // skeleton data. The components::Bag could produce stand-alone month fields,
477 // but since the CLDR does not have them, only Month::Format symbols are
478 // used for matching.
479 skeleton_field.symbol != FieldSymbol::Month(fields::Month::StandAlone)
480 );
481
482 match skeleton_field.symbol.skeleton_cmp(requested_field.symbol) {
483 Ordering::Less => {
484 // Keep searching for a matching skeleton field.
485 skeleton_fields.next();
486 distance += SKELETON_EXTRA_SYMBOL;
487 continue;
488 }
489 Ordering::Greater => {
490 // The requested field symbol is missing from the skeleton.
491 distance += REQUESTED_SYMBOL_MISSING;
492 missing_fields += 1;
493 requested_fields.next();
494 continue;
495 }
496 _ => (),
497 }
498
499 distance += if requested_field == skeleton_field {
500 NO_DISTANCE
501 } else if requested_field.symbol != skeleton_field.symbol {
502 SUBSTANTIAL_DIFFERENCES_DISTANCE
503 } else if requested_field.get_length_type() != skeleton_field.get_length_type()
504 {
505 TEXT_VS_NUMERIC_DISTANCE
506 } else {
507 WIDTH_MISMATCH_DISTANCE
508 };
509
510 requested_fields.next();
511 skeleton_fields.next();
512 }
513 (None, Some(_)) => {
514 // The skeleton has additional fields that we are not matching.
515 distance += SKELETON_EXTRA_SYMBOL;
516 skeleton_fields.next();
517 }
518 (Some(_), None) => {
519 // The skeleton is missing requested fields.
520 distance += REQUESTED_SYMBOL_MISSING;
521 requested_fields.next();
522 missing_fields += 1;
523 }
524 (None, None) => {
525 break;
526 }
527 }
528 }
529
530 if distance < closest_distance {
531 closest_distance = distance;
532 closest_match = Some(SkeletonMatch {
533 skeleton,
534 value,
535 distance,
536 missing_fields,
537 });
538 }
539 }
540
541 closest_match
542 }
543
544 /// Returns whether the match is considered a bad fit for a single-field request.
545 ///
546 /// This occurs when a single field was requested (e.g., only weekday `E`) but the best
547 /// available match either includes extra fields (e.g., `MEd` which adds month and day)
548 /// or has a substantial mismatch (e.g., text vs numeric).
549 pub fn is_bad_match_for_single_field(fields: &[Field], distance: u32) -> bool {
550 fields.len() == 1 && distance >= TEXT_VS_NUMERIC_DISTANCE
551 }
552
553 /// A partial implementation of the [UTS 35 skeleton matching algorithm](https://unicode.org/reports/tr35/tr35-dates.html#Matching_Skeletons).
554 ///
555 /// The following is implemented:
556 ///
557 /// * Compute a score based on the best possible match for the given fields.
558 /// * Select the skeleton with highest score.
559 /// * Modify the resulting pattern to have fields of the same length. For example requesting
560 /// a skeleton "yMMMMd" can have a best match of ["yMMMd", "d MMM y"]. This pattern should
561 /// then be modified to use the requested length to produce a pattern "d MMMM y".
562 /// However, fields should not be changed from numeric to text.
563 ///
564 /// The following is not implemented:
565 ///
566 /// * 2.6.2.2 Missing Skeleton Fields
567 /// - TODO(#586) - Using the CLDR appendItems field. Note: There is not agreement yet on how
568 /// much of this step to implement. See the issue for more information.
569 ///
570 /// # Panics
571 ///
572 /// Panics if `prefer_matched_pattern` is set to true in a non-datagen mode.
573 ///
574 /// <div class="stab unstable">
575 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
576 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
577 /// to be stable, their Rust representation might not be. Use with caution.
578 /// </div>
579 pub fn get_best_available_format_pattern<'data>(
580 skeletons: &BTreeMap<reference::Skeleton, PluralElements<runtime::Pattern<'data>>>,
581 fields: &[Field],
582 prefer_matched_pattern: bool,
583 ) -> BestSkeleton<PluralElements<runtime::Pattern<'data>>> {
584 let matched = find_best_skeleton(skeletons, fields);
585 let closest_distance = matched.as_ref().map(|m| m.distance).unwrap_or(u32::MAX);
586 let closest_missing_fields = matched.as_ref().map(|m| m.missing_fields).unwrap_or(0);
587
588 if !prefer_matched_pattern
589 && is_bad_match_for_single_field(fields, closest_distance)
590 && let [field] = fields
591 {
592 // A single field was requested and the best pattern either includes extra fields or can't be adjusted to match
593 // (e.g. text vs numeric). We return the field instead of the matched pattern.
594 return BestSkeleton::AllFieldsMatch(
595 PluralElements::new(runtime::Pattern::from(vec![PatternItem::Field(*field)])),
596 SkeletonQuality(closest_distance),
597 );
598 }
599
600 let Some(matched) = matched else {
601 return BestSkeleton::NoMatch;
602 };
603
604 if closest_missing_fields == fields.len() {
605 return BestSkeleton::NoMatch;
606 }
607
608 let mut closest_format_pattern = matched.value.clone();
609
610 if closest_distance == NO_DISTANCE {
611 return BestSkeleton::AllFieldsMatch(
612 closest_format_pattern,
613 SkeletonQuality(closest_distance),
614 );
615 }
616
617 // Modify the resulting pattern to have fields of the same length.
618 #[allow(clippy::panic)] // guards against running this branch in non-datagen mode.
619 if prefer_matched_pattern {
620 #[cfg(not(feature = "datagen"))]
621 panic!("This code branch should only be run when transforming provider code.");
622 } else {
623 closest_format_pattern.for_each_mut(|pattern| {
624 adjust_pattern_field_lengths(fields, pattern);
625 });
626 }
627
628 if closest_distance >= SKELETON_EXTRA_SYMBOL {
629 return BestSkeleton::MissingOrExtraFields(
630 closest_format_pattern,
631 SkeletonQuality(closest_distance),
632 );
633 }
634
635 BestSkeleton::AllFieldsMatch(closest_format_pattern, SkeletonQuality(closest_distance))
636 }