Debian Codegraph @

debian/rust-vendor/icu_segmenter/src/rule_segmenter_v2.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 //! Experimental reimplementations
6
7 use crate::complex::ComplexIterator;
8 use crate::provider::{
9 Acceptance, ComplexScript, SegmenterStateMachine, SegmenterStateMachineOverride, Symbol,
10 };
11 use crate::scaffold::RuleBreakType;
12 use smallvec::SmallVec;
13
14 pub(crate) trait ComplexHandler<Y: RuleBreakType> {
15 const BREAK_STATUS: u8;
16 const BREAK_AT_BOUNDARIES: bool;
17 type Cache: smallvec::Array<Item = usize>;
18 type ComplexPayloads<'s>: core::fmt::Debug;
19 type ComplexPayload<'s>: core::fmt::Debug;
20
21 fn select<'data>(
22 complex_payloads: &Self::ComplexPayloads<'data>,
23 script: ComplexScript,
24 ) -> Option<Self::ComplexPayload<'data>>;
25
26 fn handle<'data, 's>(
27 complex_payload: &Self::ComplexPayload<'data>,
28 iter: &Y::IterAttr<'s>,
29 past_complex: &Y::IterAttr<'s>,
30 ) -> ComplexIterator<'data, 's, Y>;
31 }
32
33 #[derive(Debug)]
34 pub(crate) struct NoComplexHandler;
35 impl<Y: RuleBreakType> ComplexHandler<Y> for NoComplexHandler {
36 const BREAK_STATUS: u8 = 0;
37 const BREAK_AT_BOUNDARIES: bool = false;
38 type Cache = [usize; 1];
39 type ComplexPayloads<'s> = core::convert::Infallible;
40 type ComplexPayload<'s> = core::convert::Infallible;
41
42 fn select<'data>(
43 &data: &Self::ComplexPayloads<'data>,
44 _: ComplexScript,
45 ) -> Option<Self::ComplexPayload<'data>> {
46 match data {}
47 }
48
49 fn handle<'data, 's>(
50 &complex_payload: &Self::ComplexPayload<'data>,
51 _: &Y::IterAttr<'s>,
52 _: &Y::IterAttr<'s>,
53 ) -> ComplexIterator<'data, 's, Y> {
54 match complex_payload {}
55 }
56 }
57
58 /// Implements the [`Iterator`] trait over the line break opportunities of the given string.
59 ///
60 /// Lifetimes:
61 ///
62 /// - `'l` = lifetime of the [`LineSegmenter`] object from which this iterator was created
63 /// - `'s` = lifetime of the string being segmented
64 ///
65 /// The [`Iterator::Item`] is an [`usize`] representing index of a code unit
66 /// _after_ the break (for a break at the end of text, this index is the length
67 /// of the [`str`] or array of code units).
68 ///
69 /// For examples of use, see [`LineSegmenter`].
70 #[derive(Debug)]
71 pub(crate) struct RuleBreakIterator<
72 'data,
73 's,
74 Y: RuleBreakType,
75 C: ComplexHandler<Y> + ?Sized = NoComplexHandler,
76 > {
77 pub(crate) data: &'data SegmenterStateMachine<'data>,
78 pub(crate) pseudo_symbol_map: &'data zerovec::ZeroVec<'data, (Symbol, ComplexScript)>,
79 // We use `IntoIter` so that we can pop from the front in O(1) time.
80 pub(crate) cache: smallvec::IntoIter<C::Cache>,
81 pub(crate) lookahead_positions: SmallVec<[Option<Y::IterAttr<'s>>; 1]>,
82 pub(crate) remaining_input: Y::IterAttr<'s>,
83 pub(crate) last_accepting_status: u8,
84 pub(crate) complex: Option<C::ComplexPayloads<'data>>,
85 }
86
87 #[test]
88 fn test_lookahead_positions_stays_on_stack() {
89 use crate::provider::Baked;
90
91 for &SegmenterStateMachine { num_lookaheads, .. } in [
92 Baked::SINGLETON_SEGMENTER_BREAK_LINE_V2,
93 Baked::SINGLETON_SEGMENTER_BREAK_GRAPHEME_CLUSTER_V2,
94 Baked::SINGLETON_SEGMENTER_BREAK_SENTENCE_V2,
95 Baked::SINGLETON_SEGMENTER_BREAK_WORD_V2,
96 ] {
97 assert!(num_lookaheads <= 1, "{num_lookaheads}");
98 }
99 }
100
101 impl<'data, 's, Y: RuleBreakType, C: ComplexHandler<Y>> RuleBreakIterator<'data, 's, Y, C> {
102 pub(crate) fn new(
103 input: Y::IterAttr<'s>,
104 data: &'data SegmenterStateMachine<'data>,
105 tailoring: Option<&'data SegmenterStateMachineOverride<'data>>,
106 complex: Option<C::ComplexPayloads<'data>>,
107 ) -> Self
108 where
109 Y: RuleBreakType,
110 C: ComplexHandler<Y>,
111 {
112 Self {
113 data,
114 pseudo_symbol_map: tailoring
115 .map(|t| &t.pseudo_symbol_map)
116 .unwrap_or(&data.pseudo_symbol_map),
117 complex,
118 cache: SmallVec::from_elem(0, 1).into_iter(),
119 lookahead_positions: SmallVec::from_elem(None, data.num_lookaheads),
120 last_accepting_status: 0,
121 remaining_input: input,
122 }
123 }
124
125 pub(crate) fn last_accepting_status(&self) -> u8 {
126 self.last_accepting_status
127 }
128 }
129
130 impl<'s, Y: RuleBreakType, C: ComplexHandler<Y>> Iterator for RuleBreakIterator<'_, 's, Y, C> {
131 type Item = usize;
132
133 fn next(&mut self) -> Option<Self::Item> {
134 if let Some(i) = self.cache.next() {
135 return Some(i);
136 }
137
138 if Y::is_empty(&self.remaining_input) {
139 self.last_accepting_status = 0;
140 return None;
141 }
142
143 let mut state = SegmenterStateMachine::START_STATE;
144 let mut iter = self.remaining_input.clone();
145
146 // Dummy value, we don't use this until it has been replaced
147 let mut last_accepting: Y::IterAttr<'s> = iter.clone();
148 let mut last_accepting_status = 0;
149 self.lookahead_positions.fill(None);
150
151 let mut complex_state = None;
152
153 (self.remaining_input, self.last_accepting_status) = loop {
154 let (symbol, complex_script) = if let Some((_, next)) = iter.clone().next() {
155 self.symbol(next.into())
156 } else {
157 (SegmenterStateMachine::EOT_SYMBOL, ComplexScript::None)
158 };
159
160 if complex_state.is_none()
161 && let Some(complex_payloads) = self.complex.as_ref()
162 && let Some(complex_payload) = C::select(complex_payloads, complex_script)
163 {
164 let mut past_complex = iter.clone();
165 let mut last_complex = past_complex.clone();
166 past_complex.next();
167 while past_complex
168 .clone()
169 .next()
170 .is_some_and(|(_, cp)| self.symbol(cp.into()).1 == complex_script)
171 {
172 past_complex.next();
173 last_complex.next();
174 }
175
176 let complex_breaks = C::handle(&complex_payload, &iter, &past_complex);
177 self.cache = complex_breaks.collect::<SmallVec<_>>().into_iter();
178
179 if C::BREAK_AT_BOUNDARIES {
180 // `self.cache` contains a break point at the end of the run, but not at the start.
181 // Store the position of the end of the run, and return the current position
182 // for the start break point (unless it's 0, which we already returned earlier).
183 self.remaining_input = past_complex;
184 self.last_accepting_status = C::BREAK_STATUS;
185 return if Y::offset(&iter) == 0 {
186 self.cache.next()
187 } else {
188 Some(Y::offset(&iter))
189 };
190 } else {
191 // Remove the break point at the end of the run, and store `last_complex`, the location
192 // of the last complex code point of the run. We'll later restart the state machine
193 // from this code point, in order to correctly break after it.
194 self.cache.next_back();
195 complex_state = Some(last_complex);
196
197 // We keep running the state machine to figure out if there's a break point at the start.
198 }
199 }
200
201 iter.next();
202
203 if let Some(next_state) = self
204 .data
205 .transitions
206 .get(usize::from(state) + usize::from(symbol) * self.data.states.len())
207 .filter(|&s| s != SegmenterStateMachine::TRASH_STATE)
208 {
209 state = next_state;
210 } else {
211 // No transition, the break point is the last accepting state
212 break (last_accepting, last_accepting_status);
213 }
214
215 let (acceptance, lookahead) = self
216 .data
217 .states
218 .get(usize::from(state))
219 // GIGO
220 .unwrap_or((Acceptance::Continue, None));
221
222 match acceptance {
223 Acceptance::Continue => (),
224 Acceptance::Accept(status) => {
225 last_accepting = iter.clone();
226 last_accepting_status = status;
227 }
228 Acceptance::Conditional(l, status) => {
229 if let Some(Some(last)) = self.lookahead_positions.get(usize::from(l)) {
230 // Lookahead hit, the break point is the last position for `l`
231 break (last.clone(), status);
232 }
233 }
234 }
235
236 if let Some(lookahead) = lookahead
237 && let Some(p) = self.lookahead_positions.get_mut(usize::from(lookahead))
238 {
239 *p = Some(iter.clone())
240 }
241 };
242
243 let break_index = Y::offset(&self.remaining_input);
244
245 // We encountered complex text and populated the cache
246 if let Some(&first_complex_break) = self.cache.as_slice().first()
247 && let Some(last_complex_cp) = complex_state
248 {
249 self.remaining_input = last_complex_cp;
250 // return the complex break if it's before the break we calculated using the state machine
251 if first_complex_break < break_index {
252 self.last_accepting_status = C::BREAK_STATUS;
253 return self.cache.next();
254 }
255 }
256
257 Some(break_index)
258 }
259 }
260
261 impl<'data, 's, Y: RuleBreakType, C: ComplexHandler<Y>> RuleBreakIterator<'data, 's, Y, C> {
262 fn symbol(&self, cp: u32) -> (Symbol, ComplexScript) {
263 let pseudo_symbol = self.data.symbols.get32(cp);
264 if let Some(i) = pseudo_symbol.checked_sub(self.data.pseudo_symbol_shift) {
265 self.pseudo_symbol_map
266 .get(i as usize)
267 .unwrap_or((pseudo_symbol, ComplexScript::None))
268 } else {
269 (pseudo_symbol, ComplexScript::None)
270 }
271 }
272 }