-
Notifications
You must be signed in to change notification settings - Fork 211
/
Copy pathmod.rs
1558 lines (1428 loc) · 56.9 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
mod hardcoded;
#[allow(clippy::indexing_slicing, clippy::unwrap_used)] // TODO(#3958): Remove.
mod replaceable;
use crate::transliterate::provider::{FunctionCall, Rule, RuleULE, SimpleId, VarTable};
use crate::transliterate::provider::{RuleBasedTransliterator, Segment, TransliteratorRulesV1};
use crate::transliterate::transliterator::hardcoded::Case;
use alloc::borrow::Cow;
use alloc::boxed::Box;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::fmt::Debug;
use core::ops::Range;
use icu_collections::codepointinvlist::CodePointInversionList;
use icu_collections::codepointinvliststringlist::CodePointInversionListAndStringList;
use icu_locale_core::Locale;
use icu_normalizer::provider::*;
use icu_normalizer::{ComposingNormalizer, DecomposingNormalizer};
use icu_provider::prelude::*;
use litemap::LiteMap;
use replaceable::*;
use zerofrom::ZeroFrom;
use zerovec::vecs::Index32;
use zerovec::VarZeroSlice;
type Filter<'a> = CodePointInversionList<'a>;
// Thought: How about a RunTransliterator trait that is implemented for all internal types, is blanket
// implemented for CustomTransliterator, and maybe is exposed to users if they want more control?
// Actually, an alternative would be: CustomTransliterator is just &str -> String, RunTransliterator is
// (&str, allowed_range) -> String, and some RepTransliterator would just be Replaceable -> ().
/// A type that supports transliteration. Used for overrides in [`Transliterator`] - see
/// [`Transliterator::try_new_with_override_unstable`].
pub trait CustomTransliterator: Debug {
/// Transliterates the portion of the input string specified by the byte indices in the range.
///
/// The returned `String` must just be the transliteration of `input[range]`. The rest is
/// there for context, if necessary.
fn transliterate(&self, input: &str, range: Range<usize>) -> String;
}
#[derive(Debug)]
struct ComposingTransliterator(ComposingNormalizer);
impl ComposingTransliterator {
fn try_nfc<P>(provider: &P) -> Result<Self, DataError>
where
P: DataProvider<NormalizerNfdDataV1>
+ DataProvider<NormalizerNfdTablesV1>
+ DataProvider<NormalizerNfcV1>
+ ?Sized,
{
let inner = ComposingNormalizer::try_new_nfc_unstable(provider)
.map_err(|e| DataError::custom("failed to load NFC").with_debug_context(&e))?;
Ok(Self(inner))
}
fn try_nfkc<P>(provider: &P) -> Result<Self, DataError>
where
P: DataProvider<NormalizerNfkdDataV1>
+ DataProvider<NormalizerNfdTablesV1>
+ DataProvider<NormalizerNfkdTablesV1>
+ DataProvider<NormalizerNfcV1>
+ ?Sized,
{
let inner = ComposingNormalizer::try_new_nfkc_unstable(provider)
.map_err(|e| DataError::custom("failed to load NFKC").with_debug_context(&e))?;
Ok(Self(inner))
}
fn transliterate(&self, mut rep: Replaceable, _env: &Env) {
// would be cool to use `normalize_to` and pass Insertable, but we need to know the
// input string, which gets replaced by the normalized string.
if let Cow::Owned(buf) = self.0.as_borrowed().normalize(rep.as_str_modifiable()) {
rep.replace_modifiable_with_str(&buf);
} // else the input was already normalized, so no need to modify `rep`
}
}
#[derive(Debug)]
struct DecomposingTransliterator(DecomposingNormalizer);
impl DecomposingTransliterator {
fn try_nfd<P>(provider: &P) -> Result<Self, DataError>
where
P: DataProvider<NormalizerNfdDataV1> + DataProvider<NormalizerNfdTablesV1> + ?Sized,
{
let inner = DecomposingNormalizer::try_new_nfd_unstable(provider)
.map_err(|e| DataError::custom("failed to load NFD").with_debug_context(&e))?;
Ok(Self(inner))
}
fn try_nfkd<P>(provider: &P) -> Result<Self, DataError>
where
P: DataProvider<NormalizerNfkdDataV1>
+ DataProvider<NormalizerNfdTablesV1>
+ DataProvider<NormalizerNfkdTablesV1>
+ ?Sized,
{
let inner = DecomposingNormalizer::try_new_nfkd_unstable(provider)
.map_err(|e| DataError::custom("failed to load NFKD").with_debug_context(&e))?;
Ok(Self(inner))
}
fn transliterate(&self, mut rep: Replaceable, _env: &Env) {
// would be cool to use `normalize_to` and pass Insertable, but we need to know the
// input string, which gets replaced by the normalized string.
if let Cow::Owned(buf) = self.0.as_borrowed().normalize(rep.as_str_modifiable()) {
rep.replace_modifiable_with_str(&buf);
} // else the input was already normalized, so no need to modify `rep`
}
}
#[derive(Debug)]
enum InternalTransliterator {
RuleBased(DataPayload<TransliteratorRulesV1>),
Composing(ComposingTransliterator),
Decomposing(DecomposingTransliterator),
Hex(hardcoded::HexTransliterator),
Null,
Remove,
Dyn(Box<dyn CustomTransliterator>),
}
impl InternalTransliterator {
fn transliterate(&self, mut rep: Replaceable, env: &Env) {
match self {
Self::RuleBased(rbt) => rbt.get().transliterate(rep, env),
// TODO(#3910): internal hardcoded transliterators
Self::Composing(t) => t.transliterate(rep, env),
Self::Decomposing(t) => t.transliterate(rep, env),
Self::Hex(t) => t.transliterate(rep),
Self::Null => (),
Self::Remove => rep.replace_modifiable_with_str(""),
Self::Dyn(custom) => {
let replacement = custom.transliterate(rep.as_str(), rep.allowed_range());
rep.replace_modifiable_with_str(&replacement)
}
}
}
}
type Env = LiteMap<String, InternalTransliterator>;
/// A `Transliterator` allows transliteration based on [UTS #35 transform rules](https://unicode.org/reports/tr35/tr35-general.html#Transforms),
/// including overrides with custom implementations.
///
/// # Examples
///
/// A transliterator with a custom alias referenced by another:
///
/// ```
/// use icu::experimental::transliterate::{Transliterator, CustomTransliterator, RuleCollection};
/// use icu::locale::Locale;
///
/// // Set up a transliterator with 3 custom rules.
/// // Note: These rules are for demonstration purposes only! Do not use.
///
/// // 1. Main entrypoint: a chain of several transliterators
/// let mut collection = RuleCollection::default();
/// collection.register_source(
/// &"und-t-und-x0-custom".parse().unwrap(),
/// "::NFD; ::FlattenLowerUmlaut; ::[:Nonspacing_Mark:] Remove; ::AsciiUpper; ::NFC;".to_string(),
/// [],
/// false,
/// true,
/// );
///
/// // 2. A custom ruleset that expands lowercase umlauts
/// collection.register_source(
/// &"und-t-und-x0-dep1".parse().unwrap(),
/// r#"
/// [ä {a \u0308}] → ae;
/// [ö {o \u0308}] → oe;
/// [ü {u \u0308}] → ue;
/// "#.to_string(),
/// ["Any-FlattenLowerUmlaut"],
/// false,
/// true,
/// );
///
/// // 3. A custom transliterator that uppercases all ASCII characters
/// #[derive(Debug)]
/// struct AsciiUpperTransliterator;
/// impl CustomTransliterator for AsciiUpperTransliterator {
/// fn transliterate(&self, input: &str, range: core::ops::Range<usize>) -> String {
/// input.to_ascii_uppercase()
/// }
/// }
/// collection.register_aliases(
/// &"und-t-und-x0-dep2".parse().unwrap(),
/// ["Any-AsciiUpper"],
/// );
///
/// // Create a transliterator from the main entrypoint:
/// let provider = collection.as_provider();
/// let t = Transliterator::try_new_with_override_unstable(
/// &provider,
/// &provider,
/// &"und-t-und-x0-custom".parse().unwrap(),
/// |locale| locale.normalizing_eq("und-t-und-x0-dep2").then_some(Ok(Box::new(AsciiUpperTransliterator))),
/// )
/// .unwrap();
///
/// // Test the behavior:
/// // - The uppercase 'Ü' is stripped of its umlaut
/// // - The lowercase 'ä' is expanded to "ae"
/// // - All ASCII characters are uppercased: not 'ß', which is not ASCII
/// let r = t.transliterate("Übermäßig".to_string());
/// assert_eq!(r, "UBERMAEßIG");
/// ```
#[derive(Debug)]
pub struct Transliterator {
transliterator: DataPayload<TransliteratorRulesV1>,
env: Env,
}
impl Transliterator {
/// Construct a [`Transliterator`] from the given [`Locale`].
///
/// # Examples
/// ```
/// use icu::experimental::transliterate::Transliterator;
/// // BCP-47-T ID for Bengali to Arabic transliteration
/// let locale = "und-Arab-t-und-beng".parse().unwrap();
/// let t = Transliterator::try_new(&locale).unwrap();
/// let output = t.transliterate("অকার্যতানাযা".to_string());
///
/// assert_eq!(output, "اكاريتانايا");
/// ```
#[cfg(feature = "compiled_data")]
pub fn try_new(locale: &Locale) -> Result<Self, DataError> {
Self::try_new_unstable(
&crate::provider::Baked,
&icu_normalizer::provider::Baked,
locale,
)
}
#[cfg(feature = "serde")]
#[doc = icu_provider::gen_buffer_unstable_docs!(BUFFER, Self::try_new)]
pub fn try_new_with_buffer_provider(
provider: &(impl BufferProvider + ?Sized),
locale: &Locale,
) -> Result<Self, DataError> {
Self::try_new_unstable(
&provider.as_deserializing(),
&provider.as_deserializing(),
locale,
)
}
#[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_new)]
pub fn try_new_unstable<PT, PN>(
transliterator_provider: &PT,
normalizer_provider: &PN,
locale: &Locale,
) -> Result<Self, DataError>
where
PT: DataProvider<TransliteratorRulesV1> + ?Sized,
PN: DataProvider<NormalizerNfdDataV1>
+ DataProvider<NormalizerNfkdDataV1>
+ DataProvider<NormalizerNfdTablesV1>
+ DataProvider<NormalizerNfkdTablesV1>
+ DataProvider<NormalizerNfcV1>
+ ?Sized,
{
Self::internal_try_new_with_override_unstable(
locale,
None::<&fn(&Locale) -> Option<Result<Box<dyn CustomTransliterator>, DataError>>>,
transliterator_provider,
normalizer_provider,
)
}
/// Construct a [`Transliterator`] from the given [`Locale`] using overrides provided
/// by `lookup`.
///
/// This allows clients to override the nested transliterators used by this transliterator.
/// Any nested transliterator will first try to be loaded with `lookup`, and only fall back
/// to the nested transliterator defined by the data if it returns `None`.
/// See [`CustomTransliterator`].
///
/// # Example
/// Overriding `"de-t-de-d0-ascii"`'s dependency on `"und-t-und-Latn-d0-ascii"`:
/// ```
/// use core::ops::Range;
/// use icu::experimental::transliterate::{
/// CustomTransliterator, Transliterator,
/// };
/// use icu::locale::Locale;
///
/// #[derive(Debug)]
/// struct FunkyGermanToAscii;
/// impl CustomTransliterator for FunkyGermanToAscii {
/// fn transliterate(
/// &self,
/// input: &str,
/// allowed_range: Range<usize>,
/// ) -> String {
/// input[allowed_range].replace("oeverride", "overridden")
/// }
/// }
///
/// let override_locale: Locale = "und-t-und-Latn-d0-ascii".parse().unwrap();
/// let locale = "de-t-de-d0-ascii".parse().unwrap();
/// let t = Transliterator::try_new_with_override(&locale, |locale| {
/// override_locale
/// .eq(locale)
/// .then_some(Ok(Box::new(FunkyGermanToAscii)))
/// })
/// .unwrap();
/// let output = t.transliterate("This is an överride example".to_string());
///
/// assert_eq!(output, "This is an overridden example");
/// ```
#[cfg(feature = "compiled_data")]
pub fn try_new_with_override<F>(locale: &Locale, lookup: F) -> Result<Self, DataError>
where
F: Fn(&Locale) -> Option<Result<Box<dyn CustomTransliterator>, DataError>>,
{
Self::try_new_with_override_unstable(
&crate::provider::Baked,
&icu_normalizer::provider::Baked,
locale,
lookup,
)
}
#[cfg(feature = "serde")]
#[doc = icu_provider::gen_buffer_unstable_docs!(BUFFER, Self::try_new_with_override)]
pub fn try_new_with_override_with_buffer_provider<F>(
provider: &(impl BufferProvider + ?Sized),
locale: &Locale,
lookup: F,
) -> Result<Self, DataError>
where
F: Fn(&Locale) -> Option<Result<Box<dyn CustomTransliterator>, DataError>>,
{
Self::try_new_with_override_unstable(
&provider.as_deserializing(),
&provider.as_deserializing(),
locale,
lookup,
)
}
#[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_new_with_override)]
pub fn try_new_with_override_unstable<PT, PN, F>(
transliterator_provider: &PT,
normalizer_provider: &PN,
locale: &Locale,
lookup: F,
) -> Result<Transliterator, DataError>
where
PT: DataProvider<TransliteratorRulesV1> + ?Sized,
PN: DataProvider<NormalizerNfdDataV1>
+ DataProvider<NormalizerNfkdDataV1>
+ DataProvider<NormalizerNfdTablesV1>
+ DataProvider<NormalizerNfkdTablesV1>
+ DataProvider<NormalizerNfcV1>
+ ?Sized,
F: Fn(&Locale) -> Option<Result<Box<dyn CustomTransliterator>, DataError>>,
{
Self::internal_try_new_with_override_unstable(
locale,
Some(&lookup),
transliterator_provider,
normalizer_provider,
)
}
fn internal_try_new_with_override_unstable<PN, PT, F>(
locale: &Locale,
lookup: Option<&F>,
transliterator_provider: &PT,
normalizer_provider: &PN,
) -> Result<Transliterator, DataError>
where
PT: DataProvider<TransliteratorRulesV1> + ?Sized,
PN: DataProvider<NormalizerNfdDataV1>
+ DataProvider<NormalizerNfkdDataV1>
+ DataProvider<NormalizerNfdTablesV1>
+ DataProvider<NormalizerNfkdTablesV1>
+ DataProvider<NormalizerNfcV1>
+ ?Sized,
F: Fn(&Locale) -> Option<Result<Box<dyn CustomTransliterator>, DataError>>,
{
let mut env = LiteMap::new();
let transliterator = Transliterator::load_rbt(
#[allow(clippy::unwrap_used)] // infallible
DataMarkerAttributes::try_from_str(&locale.to_string().to_ascii_lowercase()).unwrap(),
lookup,
transliterator_provider,
normalizer_provider,
false,
&mut env,
)?;
Ok(Transliterator {
transliterator,
env,
})
}
fn load_rbt<PT, PN, F>(
marker_attributes: &DataMarkerAttributes,
lookup: Option<&F>,
transliterator_provider: &PT,
normalizer_provider: &PN,
allow_internal: bool,
env: &mut LiteMap<String, InternalTransliterator>,
) -> Result<DataPayload<TransliteratorRulesV1>, DataError>
where
PT: DataProvider<TransliteratorRulesV1> + ?Sized,
PN: DataProvider<NormalizerNfdDataV1>
+ DataProvider<NormalizerNfkdDataV1>
+ DataProvider<NormalizerNfdTablesV1>
+ DataProvider<NormalizerNfkdTablesV1>
+ DataProvider<NormalizerNfcV1>
+ ?Sized,
F: Fn(&Locale) -> Option<Result<Box<dyn CustomTransliterator>, DataError>>,
{
let req = DataRequest {
id: DataIdentifierBorrowed::for_marker_attributes(marker_attributes),
..Default::default()
};
let transliterator = transliterator_provider.load(req)?.payload;
if !allow_internal && !transliterator.get().visibility {
return Err(DataError::custom("internal only transliterator"));
}
// Avoid recursive load
env.insert(marker_attributes.to_string(), InternalTransliterator::Null);
for dep in transliterator.get().deps() {
if !env.contains_key(&*dep) {
// Load the transliterator, by checking
let internal_t =
// a) hardcoded specials
Transliterator::load_special(&dep, normalizer_provider)
// b) the user-provided override
.or_else(|| Some(lookup?(&dep.parse().ok()?)?.map(InternalTransliterator::Dyn)))
// c) the data
.unwrap_or_else(|| {
Transliterator::load_rbt(
#[allow(clippy::unwrap_used)] // infallible
DataMarkerAttributes::try_from_str(&dep.to_ascii_lowercase()).unwrap(),
lookup,
transliterator_provider,
normalizer_provider,
true,
env,
).map(InternalTransliterator::RuleBased)
})?;
env.insert(dep.to_string(), internal_t);
}
}
Ok(transliterator)
}
fn load_special<P>(
special: &str,
normalizer_provider: &P,
) -> Option<Result<InternalTransliterator, DataError>>
where
P: DataProvider<NormalizerNfdDataV1>
+ DataProvider<NormalizerNfkdDataV1>
+ DataProvider<NormalizerNfdTablesV1>
+ DataProvider<NormalizerNfkdTablesV1>
+ DataProvider<NormalizerNfcV1>
+ ?Sized,
{
// TODO(#3909, #3910): add more
match special {
"any-nfc" => Some(
ComposingTransliterator::try_nfc(normalizer_provider)
.map(InternalTransliterator::Composing),
),
"any-nfkc" => Some(
ComposingTransliterator::try_nfkc(normalizer_provider)
.map(InternalTransliterator::Composing),
),
"any-nfd" => Some(
DecomposingTransliterator::try_nfd(normalizer_provider)
.map(InternalTransliterator::Decomposing),
),
"any-nfkd" => Some(
DecomposingTransliterator::try_nfkd(normalizer_provider)
.map(InternalTransliterator::Decomposing),
),
"any-null" => Some(Ok(InternalTransliterator::Null)),
"any-remove" => Some(Ok(InternalTransliterator::Remove)),
"any-lower" => Some(Err(DataError::custom("any-lower not implemented"))),
"any-upper" => Some(Err(DataError::custom("any-upper not implemented"))),
"any-title" => Some(Err(DataError::custom("any-title not implemented"))),
"any-hex/unicode" => Some(Ok(InternalTransliterator::Hex(
hardcoded::HexTransliterator::new("U+", "", 4, Case::Upper),
))),
"any-hex/rust" => Some(Ok(InternalTransliterator::Hex(
hardcoded::HexTransliterator::new("\\u{", "}", 2, Case::Lower),
))),
"any-hex/xml" => Some(Ok(InternalTransliterator::Hex(
hardcoded::HexTransliterator::new("&#x", ";", 1, Case::Upper),
))),
"any-hex/perl" => Some(Ok(InternalTransliterator::Hex(
hardcoded::HexTransliterator::new("\\x{", "}", 1, Case::Upper),
))),
"any-hex/plain" => Some(Ok(InternalTransliterator::Hex(
hardcoded::HexTransliterator::new("", "", 4, Case::Upper),
))),
_ => None,
}
}
// Before stabilization, consider the input type we want to accept here. We might want to
// use a data structure internally that works nicely with a &str, but if we don't, a String
// is good to accept because the user might already have one.
/// Transliterates `input` and returns its transliteration.
pub fn transliterate(&self, input: String) -> String {
// Thought: Seems too much work for the benefits, but maybe have a Cow buffer instead?
// Insertable would only actually to_owned if the replaced bytes differ from the ones already there
let mut buffer = TransliteratorBuffer::from_string(input);
let rep = Replaceable::new(&mut buffer);
self.transliterator.get().transliterate(rep, &self.env);
buffer.into_string()
}
}
impl RuleBasedTransliterator<'_> {
/// Transliteration using rules works as follows:
/// 1. Split the input modifiable range of the Replaceable according into runs according to self.filter
/// 2. Transliterate each run in sequence
/// i. Transliterate the first id_group, then the first rule_group, then the second id_group, etc.
fn transliterate(&self, mut rep: Replaceable, env: &Env) {
// assumes the cursor is at the right position.
rep.for_each_run(&self.filter, |run| {
// eprintln!("got RBT filtered_run: {run:?}");
for (id_group, rule_group) in self.id_group_list.iter().zip(self.rule_group_list.iter())
{
// first handle id_group
for single_id in id_group.iter() {
let id = SimpleId::zero_from(single_id);
id.transliterate(run.child(), env);
}
// then handle rule_group
let rule_group = RuleGroup::from(rule_group);
rule_group.transliterate(run.child(), &self.variable_table, env);
}
// eprintln!("finished RBT filtered_run transliteration: {run:?}")
});
}
}
impl SimpleId<'_> {
fn transliterate(&self, mut rep: Replaceable, env: &Env) {
// eprintln!("transliterating SimpleId: {self:?}");
// definitely loaded in the constructor
let inner = env.get(self.id.as_ref()).unwrap();
rep.for_each_run(&self.filter, |run| {
// eprintln!("transliterating SimpleId run: {rep:?}");
inner.transliterate(run.child(), env)
})
}
}
struct RuleGroup<'a> {
rules: &'a VarZeroSlice<RuleULE, Index32>,
}
impl<'a> RuleGroup<'a> {
fn from(rules: &'a VarZeroSlice<RuleULE, Index32>) -> Self {
Self { rules }
}
fn transliterate(&self, mut rep: Replaceable, vt: &VarTable, env: &Env) {
// no need to split into runs, because a RuleGroup has no filters.
if self.rules.is_empty() {
// empty rule group, nothing to do
return;
}
// while the cursor has not reached the end yet, keep trying to apply each rule in order.
// when a rule matches, apply its replacement and move the cursor according to the replacement
// note that we're stopping transliteration at the end _even though empty rules might still match_.
// this behavior is copied from ICU4C/J.
'main: while !rep.is_finished() {
// eprintln!("ongoing RuleGroup transliteration:\n{rep:?}");
for rule in self.rules.iter() {
let rule: Rule = Rule::zero_from(rule);
// eprintln!("trying rule: {rule:?}");
let matcher = rep.start_match();
if let Some((data, matcher)) = rule.matches(matcher, vt) {
rule.apply(matcher.finish_match(), data, vt, env);
// eprintln!("finished applying replacement: {rep:?}");
// eprintln!("applied rule!");
// rule application is responsible for updating the cursor
continue 'main;
}
}
// eprintln!("no rule matched, moving cursor forward");
// no rule matched, so just move the cursor forward by one code point
rep.step_cursor();
}
}
}
impl Rule<'_> {
/// Applies this rule's replacement using the given [`MatchData`]. Updates the cursor of the
/// current run.
fn apply(&self, mut dest: Insertable, data: MatchData, vt: &VarTable, env: &Env) {
// note: this could be precomputed ignoring segments and function calls.
// A `rule.used_segments` ZeroVec<u16> could be added at compile time,
// which would make it easier to take segments into account at runtime.
// there is no easy way to estimate the size of function calls, though.
// TODO(#3957): benchmark with and without this optimization
let replacement_size_estimate = estimate_replacement_size(&self.replacer, &data, vt);
dest.apply_size_hint(replacement_size_estimate);
replace_str_with_specials(&self.replacer, &mut dest, &data, vt, env);
}
/// Returns `None` if there is no match. If there is a match, returns the associated
/// [`MatchData`] and [`RepMatcher`].
// Thought: RepMatcher<true> could be "FinishedRepMatcher"? but we can still match post..
fn matches<'r1, 'r2>(
&self,
mut matcher: RepMatcher<'r1, 'r2, false>,
vt: &VarTable,
) -> Option<(MatchData, RepMatcher<'r1, 'r2, true>)> {
let mut match_data = MatchData::new();
if !self.ante_matches(&mut matcher, &mut match_data, vt) {
return None;
}
if !self.key_matches(&mut matcher, &mut match_data, vt) {
return None;
}
let mut matcher = matcher.finish_key();
if !self.post_matches(&mut matcher, &mut match_data, vt) {
return None;
}
Some((match_data, matcher))
}
/// Returns whether the ante context matches or not. Fills in `match_data` if applicable.
///
/// This uses reverse matching.
fn ante_matches(
&self,
matcher: &mut impl Utf8Matcher<Reverse>,
match_data: &mut MatchData,
vt: &VarTable,
) -> bool {
if self.ante.is_empty() {
// fast path for empty queries, which always match
return true;
}
rev_match_str_with_specials(&self.ante, matcher, match_data, vt)
}
/// Returns whether the post context matches or not. Fills in `match_data` if applicable.
///
/// This uses forward matching.
fn post_matches(
&self,
matcher: &mut impl Utf8Matcher<Forward>,
match_data: &mut MatchData,
vt: &VarTable,
) -> bool {
if self.post.is_empty() {
// fast path for empty queries, which always match
return true;
}
match_str_with_specials(&self.post, matcher, match_data, vt)
}
/// Returns whether the post context matches or not. Fills in `match_data` if applicable.
///
/// This uses forward matching.
fn key_matches(
&self,
matcher: &mut impl Utf8Matcher<Forward>,
match_data: &mut MatchData,
vt: &VarTable,
) -> bool {
if self.key.is_empty() {
// fast path for empty queries, which always match
return true;
}
match_str_with_specials(&self.key, matcher, match_data, vt)
}
}
/// Returns the index of the first special construct that is encoded as a private use char in `s`,
/// if there is one. Returns `None` if the passed string is pure
/// (contains no encoded special constructs).
fn find_special(s: &str) -> Option<usize> {
// note: full-match (i.e., if this function returns Some(_) or None, could be
// precomputed + stored at datagen time (there could eg be a reserved char that is at the
// start/end of key <=> key is completely pure)
s.char_indices()
.find(|(_, c)| VarTable::ENCODE_RANGE.contains(c))
.map(|(i, _)| i)
}
/// Returns the index of the char to the right of the first (from the right) special construct
/// encoded as a private use char. Returns `None` if the passed string is pure
/// (contains no encoded special constructs).
fn rev_find_special(s: &str) -> Option<usize> {
s.char_indices()
.rfind(|(_, c)| VarTable::ENCODE_RANGE.contains(c))
.map(|(i, c)| i + c.len_utf8())
}
/// Recursively estimates the size of the replacement string.
fn estimate_replacement_size(replacement: &str, data: &MatchData, vt: &VarTable) -> usize {
let mut size;
let replacement_tail;
match find_special(replacement) {
None => return replacement.len(),
Some(idx) => {
size = idx;
replacement_tail = &replacement[idx..];
}
}
for rep_c in replacement_tail.chars() {
if !VarTable::ENCODE_RANGE.contains(&rep_c) {
// regular char
size += rep_c.len_utf8();
continue;
}
// must be special replacer
let replacer = match vt.lookup_replacer(rep_c) {
Some(replacer) => replacer,
None => {
debug_assert!(false, "invalid encoded special {:?}", rep_c);
// GIGO behavior. we just skip invalid encodings
continue;
}
};
size += replacer.estimate_size(data, vt);
}
size
}
/// Applies the replacements from the `replacement`, which may contain encoded special replacers, to `dest`,
/// including non-default cursor updates.
fn replace_str_with_specials(
replacement: &str,
dest: &mut Insertable,
data: &MatchData,
vt: &VarTable,
env: &Env,
) {
let replacement = match find_special(replacement) {
None => {
// pure string
dest.push_str(replacement);
return;
}
Some(idx) => {
dest.push_str(&replacement[..idx]);
&replacement[idx..]
}
};
for rep_c in replacement.chars() {
if !VarTable::ENCODE_RANGE.contains(&rep_c) {
// regular char
dest.push(rep_c);
continue;
}
// must be special replacer
let replacer = match vt.lookup_replacer(rep_c) {
Some(replacer) => replacer,
None => {
debug_assert!(false, "invalid encoded special {:?}", rep_c);
// GIGO behavior. we just skip invalid encodings
continue;
}
};
replacer.replace(dest, data, vt, env);
}
}
/// Tries to match `query`, which may contain encoded special matchers, on `matcher`. Fills in `match_data` if applicable.
fn match_str_with_specials(
query: &str,
matcher: &mut impl Utf8Matcher<Forward>,
match_data: &mut MatchData,
vt: &VarTable,
) -> bool {
// eprintln!("trying to match query {query:?} on input {matcher:?}");
let query = match find_special(query) {
None => {
// pure string
return matcher.match_and_consume_str(query);
}
Some(idx) => {
if !matcher.match_and_consume_str(&query[..idx]) {
return false;
}
&query[idx..]
}
};
// iterate char-by-char, and try to match each char
// note: might be good to avoid the UTF-8 => char conversion?
for query_c in query.chars() {
if !VarTable::ENCODE_RANGE.contains(&query_c) {
// regular char
if !matcher.match_and_consume_char(query_c) {
return false;
}
continue;
}
// must be special matcher
let special_matcher = match vt.lookup_matcher(query_c) {
Some(matcher) => matcher,
None => {
debug_assert!(false, "invalid encoded special {:?}", query_c);
// GIGO behavior. we just skip invalid encodings
continue;
}
};
if !special_matcher.matches(matcher, match_data, vt) {
return false;
}
}
// matched the full query string successfully
true
}
/// Tries to match `query`, which may contain encoded special matchers, on `matcher` from the right. Fills in `match_data` if applicable.
fn rev_match_str_with_specials(
query: &str,
matcher: &mut impl Utf8Matcher<Reverse>,
match_data: &mut MatchData,
vt: &VarTable,
) -> bool {
let query = match rev_find_special(query) {
None => {
// pure string
return matcher.match_and_consume_str(query);
}
Some(idx) => {
if !matcher.match_and_consume_str(&query[idx..]) {
return false;
}
&query[..idx]
}
};
// iterate char-by-char, and try to match each char
// note: might be good to avoid the UTF-8 => char conversion?
for query_c in query.chars().rev() {
if !VarTable::ENCODE_RANGE.contains(&query_c) {
// regular char
if !matcher.match_and_consume_char(query_c) {
return false;
}
continue;
}
// must be special matcher
let special_matcher = match vt.lookup_matcher(query_c) {
Some(matcher) => matcher,
None => {
debug_assert!(false, "invalid encoded special {:?}", query_c);
// GIGO behavior. we just skip invalid encodings
continue;
}
};
if !special_matcher.rev_matches(matcher, match_data, vt) {
return false;
}
}
// matched the full query string successfully
true
}
/// Stores the state for a single conversion rule.
#[derive(Debug)]
struct MatchData {
/// Stored matches of segments.
segments: Vec<String>,
}
impl MatchData {
fn new() -> Self {
Self {
segments: Vec::new(),
}
}
fn update_segment(&mut self, i: usize, s: String) {
if i >= self.segments.len() {
self.segments.resize_with(i + 1, Default::default);
}
self.segments[i] = s;
}
fn get_segment(&self, i: usize) -> &str {
if let Some(s) = self.segments.get(i) {
return s;
}
// two cases: we have not (at runtime) encountered a segment with a high enough index
// to populate this index, in which case it is defined to be "",
// or this is GIGO, which is again ""
""
}
}
enum QuantifierKind {
ZeroOrOne,
ZeroOrMore,
OneOrMore,
}
enum SpecialMatcher<'a> {
Compound(&'a str),
Quantifier(QuantifierKind, &'a str),
Segment(Segment<'a>),
UnicodeSet(CodePointInversionListAndStringList<'a>),
AnchorStart,
AnchorEnd,
}
impl SpecialMatcher<'_> {
// Thought: a lot of duplicated code in matches and rev_matches. deduplicate.
// maybe by being generic over Direction? doesn't work for some special cases, though, like segments and sets
/// Returns whether there is a match or not. Fills in `match_data` if applicable.
fn matches(
&self,
matcher: &mut impl Utf8Matcher<Forward>,
match_data: &mut MatchData,
vt: &VarTable,
) -> bool {
match self {
Self::Compound(query) => match_str_with_specials(query, matcher, match_data, vt),
Self::UnicodeSet(set) => {
// eprintln!("checking if set {set:?} matches input {matcher:?}");
if matcher.is_empty() {
if set.contains_str("") {
return true;
}
if set.contains_str("\u{FFFF}") {
if matcher.match_end_anchor() {
return true;
}
if matcher.match_start_anchor() {
return true;
}
}
// only an empty string or an anchor could match an empty input
return false;
}
let mut max_str_match: Option<usize> = None;
for s in set.strings().iter() {
// strings are sorted. we can optimize by early-breaking when we encounter
// an `s` that is lexicographically larger than `input`
if matcher.match_str(s) {
max_str_match = max_str_match.map(|m| m.max(s.len())).or(Some(s.len()));
continue;
}
match (s.chars().next(), matcher.next_char()) {
// break early. since s_c is > input_c, we know that s > input, thus all
// strings from here on out are > input, and thus cannot match
(Some(s_c), Some(input_c)) if s_c > input_c => break,
_ => (),