Debian Codegraph @

debian/rust-vendor/icu_pattern/src/frontend/mod.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 #[cfg(feature = "databake")]
6 mod databake;
7 #[cfg(feature = "serde")]
8 pub(crate) mod serde;
9 #[cfg(feature = "zerovec")]
10 mod zerovec;
11
12 use crate::Error;
13 #[cfg(feature = "alloc")]
14 use crate::Parser;
15 #[cfg(feature = "alloc")]
16 use crate::ParserOptions;
17 use crate::common::*;
18 #[cfg(feature = "alloc")]
19 use alloc::{borrow::ToOwned, boxed::Box, string::String};
20 #[cfg(feature = "alloc")]
21 use core::str::FromStr;
22 use core::{convert::Infallible, fmt, marker::PhantomData};
23 use writeable::{PartsWrite, TryWriteable, Writeable, adapters::TryWriteableInfallibleAsWriteable};
24
25 /// A string pattern with placeholders.
26 ///
27 /// There are 2 generic parameters: `Backend` and `Store`.
28 ///
29 /// # Backend
30 ///
31 /// This determines the nature of placeholders and serialized encoding of the pattern.
32 ///
33 /// The following backends are available:
34 ///
35 /// - [`SinglePlaceholder`] for patterns with up to one placeholder: `"{0} days ago"`
36 /// - [`DoublePlaceholder`] for patterns with up to two placeholders: `"{0} days, {1} hours ago"`
37 /// - [`MultiNamedPlaceholder`] for patterns with named placeholders: `"{name} sent you a message"`
38 ///
39 /// # Format to Parts
40 ///
41 /// [`Pattern`] propagates [`Part`]s from inner writeables. In addition, it supports annotating
42 /// [`Part`]s for individual literals or placeholders via the [`PlaceholderValueProvider`] trait.
43 ///
44 /// # Examples
45 ///
46 /// Interpolating a [`SinglePlaceholder`] pattern:
47 ///
48 /// ```
49 /// use core::str::FromStr;
50 /// use icu_pattern::Pattern;
51 /// use icu_pattern::SinglePlaceholder;
52 /// use writeable::assert_writeable_eq;
53 ///
54 /// let pattern = Pattern::<SinglePlaceholder>::try_from_str(
55 /// "Hello, {0}!",
56 /// Default::default(),
57 /// )
58 /// .unwrap();
59 ///
60 /// assert_writeable_eq!(pattern.interpolate(["Alice"]), "Hello, Alice!");
61 /// ```
62 ///
63 /// [`SinglePlaceholder`]: crate::SinglePlaceholder
64 /// [`DoublePlaceholder`]: crate::DoublePlaceholder
65 /// [`MultiNamedPlaceholder`]: crate::MultiNamedPlaceholder
66 /// [`Part`]: writeable::Part
67 #[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
68 #[repr(transparent)]
69 pub struct Pattern<B: PatternBackend> {
70 _backend: PhantomData<B>,
71 /// The encoded storage
72 pub store: B::Store,
73 }
74
75 impl<B: PatternBackend> PartialEq for Pattern<B> {
76 fn eq(&self, other: &Self) -> bool {
77 self.store == other.store
78 }
79 }
80
81 impl<B: PatternBackend> fmt::Debug for Pattern<B> {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 f.debug_struct("Pattern")
84 .field("_backend", &self._backend)
85 .field("store", &&self.store)
86 .finish()
87 }
88 }
89
90 impl<B: PatternBackend> Default for &'static Pattern<B> {
91 fn default() -> Self {
92 Pattern::from_ref_store_unchecked(B::empty())
93 }
94 }
95
96 #[cfg(feature = "alloc")]
97 impl<B: PatternBackend> Default for Box<Pattern<B>>
98 where
99 Box<B::Store>: From<&'static B::Store>,
100 {
101 fn default() -> Self {
102 Pattern::from_boxed_store_unchecked(Box::from(B::empty()))
103 }
104 }
105
106 #[test]
107 fn test_defaults() {
108 assert_eq!(
109 Box::<Pattern::<crate::SinglePlaceholder>>::default(),
110 Pattern::try_from_items(core::iter::empty()).unwrap()
111 );
112 assert_eq!(
113 Box::<Pattern::<crate::DoublePlaceholder>>::default(),
114 Pattern::try_from_items(core::iter::empty()).unwrap()
115 );
116 assert_eq!(
117 Box::<Pattern::<crate::MultiNamedPlaceholder>>::default(),
118 Pattern::try_from_items(core::iter::empty()).unwrap()
119 );
120 }
121
122 #[cfg(feature = "alloc")]
123 impl<B: PatternBackend> ToOwned for Pattern<B>
124 where
125 Box<B::Store>: for<'a> From<&'a B::Store>,
126 {
127 type Owned = Box<Pattern<B>>;
128
129 fn to_owned(&self) -> Self::Owned {
130 Self::from_boxed_store_unchecked(Box::from(&self.store))
131 }
132 }
133
134 #[cfg(feature = "alloc")]
135 impl<B: PatternBackend> Clone for Box<Pattern<B>>
136 where
137 Box<B::Store>: for<'a> From<&'a B::Store>,
138 {
139 fn clone(&self) -> Self {
140 Pattern::from_boxed_store_unchecked(Box::from(&self.store))
141 }
142 }
143
144 impl<B: PatternBackend> Pattern<B> {
145 #[cfg(feature = "alloc")]
146 pub(crate) fn from_boxed_store_unchecked(store: Box<B::Store>) -> Box<Self> {
147 // Safety: Box::into_raw fulfils Box::from_raw's requirements, as Pattern<B> is
148 // repr(transparent) over B::Store, and does not have further validity constraints
149 unsafe { Box::from_raw(Box::into_raw(store) as *mut Self) }
150 }
151
152 #[doc(hidden)] // databake
153 pub const fn from_ref_store_unchecked(store: &B::Store) -> &Self {
154 // Safety: Pattern is repr(transparent) over B::Store
155 unsafe { &*(store as *const B::Store as *const Self) }
156 }
157
158 #[doc(hidden)] // B::Store is doc(hidden)
159 pub fn from_ref_store(store: &B::Store) -> Result<&Self, Error> {
160 B::validate_store(store)?;
161 Ok(Self::from_ref_store_unchecked(store))
162 }
163 }
164
165 #[cfg(feature = "alloc")]
166 impl<B> Pattern<B>
167 where
168 B: PatternBackend,
169 {
170 /// Creates a pattern from an iterator of pattern items.
171 ///
172 /// ✨ *Enabled with the `alloc` Cargo feature.*
173 ///
174 /// # Examples
175 ///
176 /// ```
177 /// use icu_pattern::Pattern;
178 /// use icu_pattern::PatternItemCow;
179 /// use icu_pattern::SinglePlaceholder;
180 /// use icu_pattern::SinglePlaceholderKey;
181 /// use std::borrow::Cow;
182 ///
183 /// Pattern::<SinglePlaceholder>::try_from_items(
184 /// [
185 /// PatternItemCow::Placeholder(SinglePlaceholderKey::Singleton),
186 /// PatternItemCow::Literal(Cow::Borrowed(" days")),
187 /// ]
188 /// .into_iter(),
189 /// )
190 /// .expect("valid pattern items");
191 /// ```
192 pub fn try_from_items<'a, I>(items: I) -> Result<Box<Self>, Error>
193 where
194 I: Iterator<Item = PatternItemCow<'a, B::PlaceholderKeyCow<'a>>>,
195 {
196 let store = B::try_from_items(items.map(Ok))?;
197 #[cfg(debug_assertions)]
198 match B::validate_store(core::borrow::Borrow::borrow(&store)) {
199 Ok(()) => (),
200 Err(e) => {
201 debug_assert!(false, "{e:?}");
202 }
203 };
204 Ok(Self::from_boxed_store_unchecked(store))
205 }
206 }
207
208 #[cfg(feature = "alloc")]
209 impl<'a, B> Pattern<B>
210 where
211 B: PatternBackend,
212 B::PlaceholderKeyCow<'a>: FromStr,
213 <B::PlaceholderKeyCow<'a> as FromStr>::Err: fmt::Debug,
214 {
215 /// Creates a pattern by parsing a syntax string.
216 ///
217 /// ✨ *Enabled with the `alloc` Cargo feature.*
218 ///
219 /// # Examples
220 ///
221 /// ```
222 /// use icu_pattern::Pattern;
223 /// use icu_pattern::SinglePlaceholder;
224 ///
225 /// // Create a pattern from a valid string:
226 /// Pattern::<SinglePlaceholder>::try_from_str("{0} days", Default::default())
227 /// .expect("valid pattern");
228 ///
229 /// // Error on an invalid pattern:
230 /// Pattern::<SinglePlaceholder>::try_from_str("{0 days", Default::default())
231 /// .expect_err("mismatched braces");
232 /// ```
233 pub fn try_from_str(pattern: &str, options: ParserOptions) -> Result<Box<Self>, Error> {
234 let parser = Parser::new(pattern, options);
235 let store = B::try_from_items(parser)?;
236 #[cfg(debug_assertions)]
237 match B::validate_store(core::borrow::Borrow::borrow(&store)) {
238 Ok(()) => (),
239 Err(e) => {
240 debug_assert!(false, "{e:?} for pattern {pattern:?}");
241 }
242 };
243 Ok(Self::from_boxed_store_unchecked(store))
244 }
245 }
246
247 impl<B> Pattern<B>
248 where
249 B: PatternBackend,
250 {
251 /// Returns an iterator over the [`PatternItem`]s in this pattern.
252 pub fn iter(&self) -> impl Iterator<Item = PatternItem<'_, B::PlaceholderKey<'_>>> + '_ {
253 B::iter_items(&self.store)
254 }
255
256 /// Returns a [`TryWriteable`] that interpolates items from the given replacement provider
257 /// into this pattern string.
258 pub fn try_interpolate<'a, P>(
259 &'a self,
260 value_provider: P,
261 ) -> impl TryWriteable<Error = P::Error> + fmt::Display + 'a
262 where
263 P: PlaceholderValueProvider<B::PlaceholderKey<'a>> + 'a,
264 {
265 WriteablePattern::<B, P> {
266 store: &self.store,
267 value_provider,
268 }
269 }
270
271 #[cfg(feature = "alloc")]
272 /// Interpolates the pattern directly to a string, returning the string or an error.
273 ///
274 /// In addition to the error, the lossy fallback string is returned in the failure case.
275 ///
276 /// ✨ *Enabled with the `alloc` Cargo feature.*
277 pub fn try_interpolate_to_string<'a, P>(
278 &'a self,
279 value_provider: P,
280 ) -> Result<String, (P::Error, String)>
281 where
282 P: PlaceholderValueProvider<B::PlaceholderKey<'a>> + 'a,
283 {
284 self.try_interpolate(value_provider)
285 .try_write_to_string()
286 .map(|s| s.into_owned())
287 .map_err(|(e, s)| (e, s.into_owned()))
288 }
289
290 /// Returns a [`Writeable`] that interpolates items from the given replacement provider
291 /// into this pattern string.
292 ///
293 /// This is defined only on infallible inputs.
294 pub fn interpolate<'a, P>(&'a self, value_provider: P) -> impl Writeable + fmt::Display + 'a
295 where
296 P: PlaceholderValueProvider<B::PlaceholderKey<'a>, Error = Infallible> + 'a,
297 {
298 TryWriteableInfallibleAsWriteable(WriteablePattern::<B, P> {
299 store: &self.store,
300 value_provider,
301 })
302 }
303
304 #[cfg(feature = "alloc")]
305 /// Interpolates the pattern directly to a string.
306 ///
307 /// This is defined only on infallible inputs.
308 ///
309 /// ✨ *Enabled with the `alloc` Cargo feature.*
310 pub fn interpolate_to_string<'a, P>(&'a self, value_provider: P) -> String
311 where
312 P: PlaceholderValueProvider<B::PlaceholderKey<'a>, Error = Infallible> + 'a,
313 {
314 self.interpolate(value_provider)
315 .write_to_string()
316 .into_owned()
317 }
318 }
319
320 struct WriteablePattern<'a, B: PatternBackend, P> {
321 store: &'a B::Store,
322 value_provider: P,
323 }
324
325 impl<'a, B, P> TryWriteable for WriteablePattern<'a, B, P>
326 where
327 B: PatternBackend,
328 P: PlaceholderValueProvider<B::PlaceholderKey<'a>>,
329 {
330 type Error = P::Error;
331
332 fn try_write_to_parts<S: PartsWrite + ?Sized>(
333 &self,
334 sink: &mut S,
335 ) -> Result<Result<(), Self::Error>, fmt::Error> {
336 let mut error = None;
337 let it = B::iter_items(self.store);
338 #[cfg(debug_assertions)]
339 let (size_hint, mut actual_len) = (it.size_hint(), 0);
340 for item in it {
341 match item {
342 PatternItem::Literal(s) => {
343 self.value_provider.map_literal(s).write_to_parts(sink)?;
344 }
345 PatternItem::Placeholder(key) => {
346 let element_writeable = self.value_provider.value_for(key);
347 if let Err(e) = element_writeable.try_write_to_parts(sink)? {
348 // Keep the first error if there was one
349 error.get_or_insert(e);
350 }
351 }
352 }
353 #[cfg(debug_assertions)]
354 {
355 actual_len += 1;
356 }
357 }
358 #[cfg(debug_assertions)]
359 {
360 debug_assert!(actual_len >= size_hint.0);
361 if let Some(max_len) = size_hint.1 {
362 debug_assert!(actual_len <= max_len);
363 }
364 }
365 if let Some(e) = error {
366 Ok(Err(e))
367 } else {
368 Ok(Ok(()))
369 }
370 }
371
372 fn writeable_length_hint(&self) -> writeable::LengthHint {
373 let mut length_hint = writeable::LengthHint::exact(0);
374 let it = B::iter_items(self.store);
375 for item in it {
376 match item {
377 PatternItem::Literal(s) => {
378 length_hint += self.value_provider.map_literal(s).writeable_length_hint();
379 }
380 PatternItem::Placeholder(key) => {
381 length_hint += self.value_provider.value_for(key).writeable_length_hint();
382 }
383 }
384 }
385 length_hint
386 }
387 }
388
389 impl<'a, B, P> fmt::Display for WriteablePattern<'a, B, P>
390 where
391 B: PatternBackend,
392 P: PlaceholderValueProvider<B::PlaceholderKey<'a>>,
393 {
394 #[inline]
395 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
396 // Discard the TryWriteable error (lossy mode)
397 self.try_write_to(f).map(|_| ())
398 }
399 }
400
401 /// A structure containing the extracted placeholder values.
402 ///
403 /// Query it using [`Self::get()`].
404 ///
405 /// <div class="stab unstable">
406 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
407 /// including in SemVer minor releases. If you find this useful, please comment on the
408 /// [tracking issue #8331](https://github.com/unicode-org/icu4x/issues/8331).
409 /// </div>
410 ///
411 /// ✨ *Enabled with the `unstable` Cargo feature.*
412 #[cfg(feature = "unstable")]
413 pub struct PlaceholderMatches<'p, 'a, B: ExtractionBackend> {
414 pub(crate) store: B::DecodedMatchesUnstable<'p, 'a>,
415 }
416
417 #[cfg(feature = "unstable")]
418 impl<'p, 'a, B: ExtractionBackend> PlaceholderMatches<'p, 'a, B> {
419 /// Gets the matched substring for the given placeholder key.
420 ///
421 /// Returns `None` if the placeholder was not present in the pattern.
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. If you find this useful, please comment on the
426 /// [tracking issue #8331](https://github.com/unicode-org/icu4x/issues/8331).
427 /// </div>
428 ///
429 /// ✨ *Enabled with the `unstable` Cargo feature.*
430 ///
431 /// # Examples
432 ///
433 /// ```
434 /// use icu_pattern::{DoublePlaceholder, DoublePlaceholderKey, Pattern};
435 ///
436 /// let pattern = Pattern::<DoublePlaceholder>::try_from_str(
437 /// "Hello, {0} and {1}!",
438 /// Default::default(),
439 /// )
440 /// .unwrap();
441 /// let matches = pattern.extract_values("Hello, Alice and Bob!").unwrap();
442 /// assert_eq!(matches.get(DoublePlaceholderKey::Place0), Some("Alice"));
443 /// assert_eq!(matches.get(DoublePlaceholderKey::Place1), Some("Bob"));
444 /// ```
445 pub fn get(&self, key: B::PlaceholderKey<'_>) -> Option<&'a str> {
446 B::get_match_unstable(&self.store, key)
447 }
448 }
449
450 #[cfg(feature = "unstable")]
451 impl<'p, B: ExtractionBackend> fmt::Debug for PlaceholderMatches<'p, '_, B>
452 where
453 for<'a> B::DecodedMatchesUnstable<'p, 'a>: fmt::Debug,
454 {
455 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
456 f.debug_struct("PlaceholderMatches")
457 .field("store", &self.store)
458 .finish()
459 }
460 }
461
462 #[cfg(feature = "unstable")]
463 impl<'p, B: ExtractionBackend> PartialEq for PlaceholderMatches<'p, '_, B>
464 where
465 for<'a> B::DecodedMatchesUnstable<'p, 'a>: PartialEq,
466 {
467 fn eq(&self, other: &Self) -> bool {
468 self.store == other.store
469 }
470 }
471
472 #[cfg(feature = "unstable")]
473 impl<'p, B: ExtractionBackend> Eq for PlaceholderMatches<'p, '_, B> where
474 for<'a> B::DecodedMatchesUnstable<'p, 'a>: Eq
475 {
476 }
477
478 #[cfg(feature = "unstable")]
479 impl<B: ExtractionBackend> Pattern<B> {
480 /// Extracts placeholder values from the formatted string.
481 ///
482 /// Returns `None` if the input string does not match the pattern.
483 ///
484 /// <div class="stab unstable">
485 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
486 /// including in SemVer minor releases. If you find this useful, please comment on the
487 /// [tracking issue #8331](https://github.com/unicode-org/icu4x/issues/8331).
488 /// </div>
489 ///
490 /// ✨ *Enabled with the `unstable` Cargo feature.*
491 ///
492 /// # Examples
493 ///
494 /// ```
495 /// use icu_pattern::{Pattern, SinglePlaceholder, SinglePlaceholderKey};
496 ///
497 /// let pattern = Pattern::<SinglePlaceholder>::try_from_str(
498 /// "Hello, {0}!",
499 /// Default::default(),
500 /// )
501 /// .unwrap();
502 /// let matches = pattern.extract_values("Hello, Alice!").unwrap();
503 /// assert_eq!(matches.get(SinglePlaceholderKey::Singleton), Some("Alice"));
504 /// ```
505 pub fn extract_values<'p, 'a>(
506 &'p self,
507 input: &'a str,
508 ) -> Option<PlaceholderMatches<'p, 'a, B>> {
509 B::extract_unstable(&self.store, input).map(|store| PlaceholderMatches { store })
510 }
511 }
512
513 #[test]
514 fn test_try_from_str_inference() {
515 use crate::SinglePlaceholder;
516 let _: Box<Pattern<SinglePlaceholder>> =
517 Pattern::try_from_str("{0} days", Default::default()).unwrap();
518 let _ = Pattern::<SinglePlaceholder>::try_from_str("{0} days", Default::default()).unwrap();
519 }