mongol_norm/written_units.rs
1//! Written-unit input APIs — a port of `normalize_written_units`,
2//! `normalize_positioned_written_units` and `_parse_written_units` from `mongol_norm/shaper.py`.
3
4use crate::duplicates::collapse;
5use crate::generated::enums::WrittenUnit;
6use crate::normalize::{is_joiner, slot_position, NormalizeTable};
7use crate::shaper::Shaper;
8use crate::tables::{Position, UnitPosition};
9use crate::Error;
10
11/// One record of [`Shaper::normalize_positioned_written_units`]: a written unit with its
12/// authoritative HUD inventory position (`Control` for `Mvs` / `Nirugu`).
13///
14/// This is an *input* type: both fields are public and it is deliberately not
15/// `#[non_exhaustive]` (unlike the crate's result types), so callers can build records with a
16/// struct literal or [`PositionedWrittenUnit::new`] and destructure them freely.
17#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
18pub struct PositionedWrittenUnit {
19 /// The written unit.
20 pub unit: WrittenUnit,
21 /// Its HUD inventory position.
22 pub position: UnitPosition,
23}
24
25impl PositionedWrittenUnit {
26 /// Build a record.
27 pub const fn new(unit: WrittenUnit, position: UnitPosition) -> PositionedWrittenUnit {
28 PositionedWrittenUnit { unit, position }
29 }
30}
31
32/// The positioned API accepts at most this many records (Python parity).
33pub const MAX_POSITIONED_RECORDS: usize = 1024;
34
35enum PositionedPart {
36 Control(WrittenUnit),
37 Chain(Vec<(WrittenUnit, Position)>),
38}
39
40/// Does `part` cursively join the chain next to it? Only a joiner control does; a neighbouring
41/// chain never does (Python tests `parts[i][0] in _JOINER_TOKENS`, and a chain part's tag is the
42/// literal `"chain"`).
43fn is_joiner_part(part: &PositionedPart) -> bool {
44 matches!(part, PositionedPart::Control(unit) if is_joiner(*unit))
45}
46
47impl Shaper {
48 /// Encode an ordered written-unit sequence (e.g. the output of [`Shaper::shape`]) as
49 /// canonical Unicode. Letter positions are inferred from order and the structural tokens;
50 /// ZWJ is emitted only where `Zwj` is present in the request. The result is accepted only if
51 /// it reshapes to exactly the requested sequence.
52 ///
53 /// An empty sequence returns `""` — without consulting the table, so it succeeds on every
54 /// locale.
55 ///
56 /// # Errors
57 ///
58 /// - [`Error::NormalizeUnsupported`] — this locale has no bundled normalize table.
59 /// - [`Error::UnsupportedWrittenUnit`] — `units[index]` is outside the table's vocabulary
60 /// (for example the Todo unit `E` on an MNG shaper). The first offender is reported.
61 /// - [`Error::NoCanonicalEncoding`] — the table covers every unit, but the sequence has no
62 /// encoding that reshapes back to it.
63 pub fn normalize_written_units(&self, units: &[WrittenUnit]) -> Result<String, Error> {
64 if units.is_empty() {
65 return Ok(String::new());
66 }
67 let table = self.table()?;
68 for (index, unit) in units.iter().enumerate() {
69 if !table.known_units.contains(unit) {
70 return Err(Error::UnsupportedWrittenUnit { index, unit: *unit });
71 }
72 }
73 // Duplicate encodings are accepted on input — `Dd`, medial `H`/`Hx` are real units in
74 // the standard and in callers' data — and folded before encoding, so they get the same
75 // canonical text as the sequence they render identically to.
76 let units = collapse(units);
77 let canonical = self.canonical_for_shape(&units)?;
78 if canonical.is_empty() || self.shape(&canonical)? != units {
79 return Err(Error::NoCanonicalEncoding);
80 }
81 Ok(canonical)
82 }
83
84 /// Encode explicit HUD-position records as canonical Unicode (the API `zvvnmod-utn57`
85 /// uses). A complete multi-record chain runs `init…fina`; an incomplete edge gets an implicit
86 /// ZWJ; a single `init` record is encoded bare where that bare letter reads back as the same
87 /// record — every consonant, whose isolated form is its initial unit — and takes a trailing
88 /// ZWJ where it would not: `A` and `I`, which the inventory also carries at `isol`, and `O`,
89 /// which has no bare spelling; single `medi` / `fina` records get the joining context their
90 /// position needs. `Mvs` and
91 /// `Nirugu` require `Control`; explicit `Zwj` is rejected; at most
92 /// [`MAX_POSITIONED_RECORDS`] records.
93 ///
94 /// # Validation order
95 ///
96 /// Checks run in a fixed order, and it is observable — callers such as `zvvnmod-utn57`
97 /// dispatch on the variant, so the *first* failing check decides which one they see:
98 ///
99 /// 1. record limit — 2000 records containing a `Zwj` is [`Error::TooManyRecords`], not
100 /// [`Error::ExplicitZwj`], and an over-limit request on a table-less locale is
101 /// [`Error::TooManyRecords`], not [`Error::NormalizeUnsupported`];
102 /// 2. explicit `Zwj` anywhere in the request;
103 /// 3. empty request — returns `""` before the table is consulted, so it succeeds on every
104 /// locale;
105 /// 4. the normalize table;
106 /// 5. per record, the control/inventory check (`Mvs` and `Nirugu` need `Control`; every other
107 /// `(unit, position)` must be in the HUD inventory), reporting the first offender;
108 /// 6. per multi-record chain, that the declared positions match the padded chain;
109 /// 7. delegation to [`Shaper::normalize_written_units`].
110 ///
111 /// # Errors
112 ///
113 /// - [`Error::TooManyRecords`], [`Error::ExplicitZwj`], [`Error::NormalizeUnsupported`],
114 /// [`Error::ControlRequiresControlPosition`], [`Error::UnsupportedPositionedUnit`],
115 /// [`Error::ChainPositionMismatch`] — as numbered above.
116 /// - Anything [`Shaper::normalize_written_units`] returns. **Its indices point into the
117 /// expanded written-unit sequence — after implicit ZWJs were inserted — not into
118 /// `records`.**
119 pub fn normalize_positioned_written_units(
120 &self,
121 records: &[PositionedWrittenUnit],
122 ) -> Result<String, Error> {
123 if records.len() > MAX_POSITIONED_RECORDS {
124 return Err(Error::TooManyRecords {
125 max: MAX_POSITIONED_RECORDS,
126 });
127 }
128 if records.iter().any(|record| record.unit == WrittenUnit::Zwj) {
129 return Err(Error::ExplicitZwj);
130 }
131 if records.is_empty() {
132 return Ok(String::new());
133 }
134 let table = self.table()?;
135 for (index, record) in records.iter().enumerate() {
136 if matches!(record.unit, WrittenUnit::Mvs | WrittenUnit::Nirugu) {
137 if record.position != UnitPosition::Control {
138 return Err(Error::ControlRequiresControlPosition {
139 index,
140 unit: record.unit,
141 });
142 }
143 continue;
144 }
145 let supported = record
146 .position
147 .as_position()
148 .is_some_and(|position| table.positioned_units.contains(&(record.unit, position)));
149 if !supported {
150 return Err(Error::UnsupportedPositionedUnit {
151 index,
152 unit: record.unit,
153 position: record.position,
154 });
155 }
156 }
157
158 let mut parts: Vec<PositionedPart> = Vec::new();
159 let mut chain: Vec<(WrittenUnit, Position)> = Vec::new();
160 for record in records {
161 match record.position.as_position() {
162 None => {
163 if !chain.is_empty() {
164 parts.push(PositionedPart::Chain(std::mem::take(&mut chain)));
165 }
166 parts.push(PositionedPart::Control(record.unit));
167 }
168 Some(position) => chain.push((record.unit, position)),
169 }
170 }
171 if !chain.is_empty() {
172 parts.push(PositionedPart::Chain(chain));
173 }
174 let mut written: Vec<WrittenUnit> = Vec::new();
175 for index in 0..parts.len() {
176 let body = match &parts[index] {
177 PositionedPart::Control(unit) => {
178 written.push(*unit);
179 continue;
180 }
181 PositionedPart::Chain(body) => body,
182 };
183 let joined_left = index > 0 && is_joiner_part(&parts[index - 1]);
184 let joined_right = index + 1 < parts.len() && is_joiner_part(&parts[index + 1]);
185 if body.len() == 1 {
186 let (unit, position) = body[0];
187 // `records.len()`, not `body.len()`: the trailing ZWJ is for a request that is
188 // NOTHING but the `init` record. `[Nirugu:control, O:init]` also has a one-unit
189 // body, but the nirugu already supplies the joining context — it must not get the
190 // ZWJ.
191 if records.len() == 1
192 && position == Position::Init
193 && self.lone_init_needs_zwj(table, unit)
194 {
195 written.extend([unit, WrittenUnit::Zwj]);
196 continue;
197 }
198 if matches!(position, Position::Medi | Position::Fina) && !joined_left {
199 written.push(WrittenUnit::Zwj);
200 }
201 written.push(unit);
202 if position == Position::Medi && !joined_right {
203 written.push(WrittenUnit::Zwj);
204 }
205 continue;
206 }
207 // One flag per side folds together the two ways a side can be non-initial/non-final:
208 // a joiner control already sits there, or the chain simply does not start at `init` /
209 // end at `fina` (so a ZWJ has to be invented). Either way the chain's positions are
210 // computed as if one extra unit padded that side, which is exactly `padded_count`.
211 let padded_left = joined_left || body[0].1 != Position::Init;
212 let padded_right = joined_right || body[body.len() - 1].1 != Position::Fina;
213 let padded_count = body.len() + usize::from(padded_left) + usize::from(padded_right);
214 // `length = 1` because each record is one written unit occupying one slot; multi-unit
215 // letters are the *encoder's* concern (`unit_partition`), not the caller's request.
216 for (offset, (_unit, position)) in body.iter().enumerate() {
217 let expected = slot_position(offset + usize::from(padded_left), 1, padded_count);
218 if *position != expected {
219 return Err(Error::ChainPositionMismatch);
220 }
221 }
222 if padded_left && !joined_left {
223 written.push(WrittenUnit::Zwj);
224 }
225 written.extend(body.iter().map(|(unit, _)| *unit));
226 if padded_right && !joined_right {
227 written.push(WrittenUnit::Zwj);
228 }
229 }
230 self.normalize_written_units(&written)
231 }
232
233 /// Does a request that is nothing but `unit` at `init` need a trailing ZWJ to read back as
234 /// `init`?
235 ///
236 /// Bare, a lone letter is an isolated chain. That is still the `init` record wherever the
237 /// isolated form *is* the initial written unit — an isolated consonant borrows it (`B`, `Ch`,
238 /// `D`, …) — so those stay bare. Two kinds of letter would read back as something else and
239 /// take the joiner (Satsrag/meco-rust#45): one the inventory also carries at `isol` under the
240 /// same bare spelling (`A`, `I`), and one with no bare spelling of its own (`O`, whose bare
241 /// letter is `U:isol`).
242 fn lone_init_needs_zwj(&self, table: &NormalizeTable, unit: WrittenUnit) -> bool {
243 table.positioned_units.contains(&(unit, Position::Isol))
244 || self.normalize_written_units(&[unit]).is_err()
245 }
246
247 /// Parse the CLI's written-unit spelling: explicit `+`-separated names (`B+Aa`) or a
248 /// compact PascalCase string with exactly one segmentation over this shaper's known units
249 /// (`BZwj`). One trailing newline is tolerated; an ambiguous compact string is rejected.
250 ///
251 /// Every name — explicit or compact — must belong to *this shaper's normalize table*, not
252 /// merely to [`WrittenUnit`]: `E` is a Todo unit, so an MNG shaper rejects it. That keeps the
253 /// reported index identical to Python's, which defers the same check to
254 /// `normalize_written_units`.
255 ///
256 /// # Errors
257 ///
258 /// - [`Error::NormalizeUnsupported`] — this locale has no bundled normalize table.
259 /// - [`Error::InvalidUnitSpec`] — the spec contains whitespace or an empty `+` field, or the
260 /// compact string has more than one segmentation.
261 /// - [`Error::UnknownWrittenUnit`] — a name is outside the table's vocabulary; on the compact
262 /// path an unsegmentable string is reported whole, at index 0.
263 pub fn parse_written_units(&self, text: &str) -> Result<Vec<WrittenUnit>, Error> {
264 let table = self.table()?;
265 parse_unit_names(text, &table.sorted_vocabulary)?
266 .into_iter()
267 .enumerate()
268 .map(|(index, name)| {
269 // Membership is tested against the TABLE's vocabulary, not merely "is this a
270 // `WrittenUnit` variant": Python leaves every name unresolved here and lets
271 // `normalize_written_units` reject the first one missing from `known_units`, so a
272 // unit the enum knows but this locale's table does not (e.g. the Todo unit `E`)
273 // must fail at Python's index too. — see shaper.py::normalize_written_units
274 name.parse::<WrittenUnit>()
275 .ok()
276 .filter(|unit| table.known_units.contains(unit))
277 .ok_or_else(|| Error::UnknownWrittenUnit {
278 index,
279 unit: name.to_owned(),
280 })
281 })
282 .collect()
283 }
284}
285
286impl Shaper {
287 /// Every written unit this shaper's normalize table can encode, plus the structural
288 /// controls (`Mvs`, `Nirugu`, `Zwj`), sorted by name.
289 ///
290 /// These are exactly the names [`Shaper::normalize_written_units`] accepts; the Python
291 /// bindings use the list to validate their input with Python-formatted messages.
292 ///
293 /// # Errors
294 ///
295 /// [`Error::NormalizeUnsupported`] — this locale has no bundled normalize table.
296 pub fn known_written_units(&self) -> Result<Vec<WrittenUnit>, Error> {
297 let table = self.table()?;
298 let mut units: Vec<WrittenUnit> = table.known_units.iter().copied().collect();
299 units.sort_by_key(|unit| unit.as_str());
300 Ok(units)
301 }
302
303 /// The HUD positioned inventory: every `(unit, position)` pair that
304 /// [`Shaper::normalize_positioned_written_units`] accepts for a letter record (letter
305 /// positions only — controls are not part of the inventory), sorted by unit name then
306 /// position.
307 ///
308 /// # Errors
309 ///
310 /// [`Error::NormalizeUnsupported`] — this locale has no bundled normalize table.
311 pub fn positioned_written_units(&self) -> Result<Vec<(WrittenUnit, Position)>, Error> {
312 let table = self.table()?;
313 let mut records: Vec<(WrittenUnit, Position)> =
314 table.positioned_units.iter().copied().collect();
315 records.sort_by_key(|(unit, position)| (unit.as_str(), position.as_str()));
316 Ok(records)
317 }
318}
319
320fn strip_one_newline(text: &str) -> &str {
321 text.strip_suffix("\r\n")
322 .or_else(|| text.strip_suffix('\n'))
323 .or_else(|| text.strip_suffix('\r'))
324 .unwrap_or(text)
325}
326
327/// Python `_parse_written_units`: explicit `+` names, or a unique compact segmentation over
328/// `vocabulary`. Returns borrowed names — slices of `text` on the `+` path, vocabulary entries on
329/// the compact path — which the caller maps to units.
330///
331/// `vocabulary` is expected in Python's `(-len, name)` order (see
332/// [`crate::normalize::NormalizeTable::sorted_vocabulary`]), but that order is *not* semantically load-bearing: the
333/// per-offset count saturates at 2 and `choice` is cleared by any second match, so the final
334/// `(count, choice)` pair is independent of iteration order. Sorting only lets the longest
335/// candidates hit the `count == 2` early `break` sooner.
336pub(crate) fn parse_unit_names<'v>(
337 text: &'v str,
338 vocabulary: &[&'v str],
339) -> Result<Vec<&'v str>, Error> {
340 let text = strip_one_newline(text);
341 if text.is_empty() {
342 return Ok(Vec::new());
343 }
344 if text.chars().any(char::is_whitespace) {
345 return Err(Error::InvalidUnitSpec(
346 "written units cannot be empty or contain whitespace".to_owned(),
347 ));
348 }
349 if text.contains('+') {
350 let units: Vec<&str> = text.split('+').collect();
351 if units
352 .iter()
353 .any(|unit| unit.is_empty() || *unit != unit.trim())
354 {
355 return Err(Error::InvalidUnitSpec(
356 "written units cannot be empty or contain whitespace; separate explicit units \
357 with '+' (for example A+Aa+B+Zwj)"
358 .to_owned(),
359 ));
360 }
361 return Ok(units);
362 }
363 // Right-to-left DP over byte offsets. Invariant: `parse_counts[i]` is the number of ways
364 // `text[i..]` segments into vocabulary units, saturated at 2 — 0 = impossible, 1 = exactly
365 // one segmentation, 2 = "two or more", i.e. ambiguous. The empty suffix has one (the empty)
366 // segmentation, hence `parse_counts[n] = 1`. `choices[i]` is the unit that starts `text[i..]`
367 // in its unique parse, plus where that unit ends.
368 let n = text.len();
369 let mut parse_counts = vec![0u8; n + 1];
370 let mut choices: Vec<Option<(&'v str, usize)>> = vec![None; n + 1];
371 parse_counts[n] = 1;
372 for offset in (0..n).rev() {
373 if !text.is_char_boundary(offset) {
374 continue; // inside a multi-byte char: no unit can start here (count stays 0)
375 }
376 let mut count = 0u8;
377 let mut choice = None;
378 for unit in vocabulary.iter() {
379 let end = offset + unit.len();
380 if end > n || !text[offset..].starts_with(unit) || parse_counts[end] == 0 {
381 continue;
382 }
383 if count == 0 && parse_counts[end] == 1 {
384 choice = Some((*unit, end));
385 } else {
386 choice = None;
387 }
388 count = (count + parse_counts[end]).min(2);
389 if count == 2 {
390 break;
391 }
392 }
393 parse_counts[offset] = count;
394 if count == 1 {
395 // `count` lands on exactly 1 only when a single match contributed, and that match
396 // took the `count == 0 && parse_counts[end] == 1` branch — any second match would
397 // both clear `choice` and push `count` to 2. So `choice` is `Some` here, which is
398 // what the `expect` below relies on.
399 choices[offset] = choice;
400 }
401 }
402 match parse_counts[0] {
403 0 => Err(Error::UnknownWrittenUnit {
404 index: 0,
405 unit: text.to_owned(),
406 }),
407 1 => {
408 let mut units = Vec::new();
409 let mut offset = 0;
410 while offset < n {
411 let (unit, end) = choices[offset].expect("a unique parse records its choice");
412 units.push(unit);
413 offset = end;
414 }
415 Ok(units)
416 }
417 _ => Err(Error::InvalidUnitSpec(
418 "compact written-unit sequence is ambiguous; separate units with '+'".to_owned(),
419 )),
420 }
421}
422
423#[cfg(test)]
424mod tests {
425 use super::*;
426
427 #[test]
428 fn ambiguous_compact_units_require_plus_separators() {
429 // Python: `_parse_written_units("AAA", {"A", "AA"})` → "ambiguous … +"
430 let error = parse_unit_names("AAA", &["AA", "A"]).unwrap_err();
431 assert!(
432 matches!(&error, Error::InvalidUnitSpec(m) if m.contains("ambiguous") && m.contains('+'))
433 );
434 assert_eq!(parse_unit_names("AA", &["AA", "A"]).unwrap_err(), error);
435 assert_eq!(
436 parse_unit_names("AAB", &["AA", "A", "B"]).unwrap_err(),
437 error
438 );
439 assert_eq!(parse_unit_names("AAB", &["AA", "B"]).unwrap(), ["AA", "B"]);
440 }
441
442 /// The `(-len, name)` order is an optimisation, not semantics: any permutation of the same
443 /// vocabulary yields the same result.
444 #[test]
445 fn vocabulary_order_does_not_change_the_parse() {
446 // {AA, B} parses "AAB" uniquely; {A, AA} makes "AAA" ambiguous. Both hold in any order.
447 for vocabulary in [["AA", "B"], ["B", "AA"]] {
448 assert_eq!(parse_unit_names("AAB", &vocabulary).unwrap(), ["AA", "B"]);
449 }
450 for vocabulary in [["AA", "A"], ["A", "AA"]] {
451 assert!(parse_unit_names("AAA", &vocabulary).is_err());
452 assert_eq!(parse_unit_names("A", &vocabulary).unwrap(), ["A"]);
453 }
454 }
455
456 #[test]
457 fn multibyte_input_never_splits_a_char() {
458 assert_eq!(
459 parse_unit_names("A\u{1820}", &["A"]).unwrap_err(),
460 Error::UnknownWrittenUnit {
461 index: 0,
462 unit: "A\u{1820}".to_owned()
463 }
464 );
465 }
466
467 #[test]
468 fn trailing_transport_newline_is_stripped_once() {
469 assert_eq!(parse_unit_names("A\r\n", &["A"]).unwrap(), ["A"]);
470 assert_eq!(parse_unit_names("A\n", &["A"]).unwrap(), ["A"]);
471 assert_eq!(parse_unit_names("\n", &["A"]).unwrap(), Vec::<&str>::new());
472 assert!(parse_unit_names("A\n\n", &["A"]).is_err());
473 }
474}