git clone https://garage44.eu/jeroen/pinnacle.git.. /text/src/bidi.rs
//! The Unicode Bidirectional Algorithm (UAX #9) for one paragraph: each
//! character's embedding level, and the order to draw them in.
//!
//! All of it: explicit embeddings, overrides and isolates (X1–X10), weak
//! and neutral types (W1–W7, N0 with paired brackets, N1–N2), implicit
//! levels (I1–I2), and the reordering of a line (L1–L2). Checked against
//! Unicode's `BidiCharacterTest.txt` (a sample in `tests/`).
use alloc::vec;
use alloc::vec::Vec;
use crate::tables;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(u8)]
pub enum Class {
L,
R,
AL,
EN,
ES,
ET,
AN,
CS,
NSM,
BN,
B,
S,
WS,
ON,
LRE,
LRO,
RLE,
RLO,
PDF,
LRI,
RLI,
FSI,
PDI,
}
use Class::*;
const CLASSES: [Class; 23] = [
L, R, AL, EN, ES, ET, AN, CS, NSM, BN, B, S, WS, ON, LRE, LRO, RLE, RLO, PDF, LRI, RLI, FSI, PDI,
];
pub fn class(c: char) -> Class {
crate::find(&tables::BIDI, c as u32).map_or(L, |i| CLASSES[usize::from(i)])
}
/// The character with the mirrored glyph, for one at an odd level (L4).
pub fn mirror(c: char) -> char {
let c32 = c as u32;
let i = tables::MIRROR.partition_point(|&(a, _)| a < c32);
match tables::MIRROR.get(i) {
Some(&(a, b)) if a == c32 => char::from_u32(b).unwrap_or(c),
_ => c,
}
}
/// Whether text in this direction needs the algorithm at all: any
/// character that is right to left, or explicit formatting.
pub fn any_rtl(text: &str) -> bool {
text.chars()
.any(|c| matches!(class(c), R | AL | AN | RLE | RLO | RLI | FSI | LRE | LRO | LRI))
}
const MAX_DEPTH: u8 = 125;
fn removed(c: Class) -> bool {
matches!(c, RLE | LRE | RLO | LRO | PDF | BN)
}
fn isolate_initiator(c: Class) -> bool {
matches!(c, LRI | RLI | FSI)
}
/// P2–P3: the level of the first strong character, isolates skipped, from
/// `start` up to the end or an unmatched PDI. `None` when there is none.
fn first_strong(classes: &[Class], start: usize) -> Option<u8> {
let mut depth = 0usize;
for &c in &classes[start..] {
match c {
LRI | RLI | FSI => depth += 1,
PDI if depth > 0 => depth -= 1,
PDI => return None,
B => return None,
L if depth == 0 => return Some(0),
R | AL if depth == 0 => return Some(1),
_ => {}
}
}
None
}
/// The paragraph's level, as P2–P3 find it: 1 when its first strong
/// character is right to left.
pub fn paragraph_level(text: &[char]) -> u8 {
let classes: Vec<Class> = text.iter().map(|&c| class(c)).collect();
first_strong(&classes, 0).unwrap_or(0)
}
/// What the algorithm found for a paragraph.
pub struct Paragraph {
pub level: u8,
/// Each character's level; a character X9 removes (embeddings,
/// boundary neutrals) has the level of the one before it.
pub levels: Vec<u8>,
/// Which characters X9 removed: they are not drawn.
pub removed: Vec<bool>,
}
/// Runs the algorithm over `text`, at paragraph level `level` (0 left to
/// right, 1 right to left), or the level its text says when `None`.
pub fn paragraph(text: &[char], level: Option<u8>) -> Paragraph {
let chars: Vec<u32> = text.iter().map(|&c| c as u32).collect();
resolve(&chars, level)
}
/// [`paragraph`] over code points, which need not be characters (the
/// conformance tests use surrogates' classes too).
pub fn resolve(chars: &[u32], level: Option<u8>) -> Paragraph {
let original: Vec<Class> = chars
.iter()
.map(|&c| char::from_u32(c).map_or(L, class))
.collect();
let original = &original[..];
let n = original.len();
let para = level.unwrap_or_else(|| first_strong(original, 0).unwrap_or(0));
let mut classes = original.to_vec();
let mut levels = vec![para; n];
// BD9: each isolate initiator's matching PDI.
let mut matching: Vec<Option<usize>> = vec![None; n];
let mut opened: Vec<usize> = Vec::new();
for (i, &c) in original.iter().enumerate() {
match c {
LRI | RLI | FSI => opened.push(i),
PDI => {
if let Some(o) = opened.pop() {
matching[o] = Some(i);
}
}
B => opened.clear(),
_ => {}
}
}
// X1–X8.
#[derive(Clone, Copy)]
struct Entry {
level: u8,
over: Option<Class>,
isolate: bool,
}
let mut stack = vec![Entry {
level: para,
over: None,
isolate: false,
}];
let (mut overflow_isolate, mut overflow_embedding, mut valid_isolate) = (0usize, 0usize, 0usize);
for i in 0..n {
let c = original[i];
let top = *stack.last().unwrap();
let next_odd = |l: u8| if l.is_multiple_of(2) { l + 1 } else { l + 2 };
let next_even = |l: u8| if l.is_multiple_of(2) { l + 2 } else { l + 1 };
match c {
RLE | LRE | RLO | LRO => {
let new = if matches!(c, RLE | RLO) {
next_odd(top.level)
} else {
next_even(top.level)
};
levels[i] = top.level;
if new <= MAX_DEPTH && overflow_isolate == 0 && overflow_embedding == 0 {
stack.push(Entry {
level: new,
over: match c {
RLO => Some(R),
LRO => Some(L),
_ => None,
},
isolate: false,
});
} else if overflow_isolate == 0 {
overflow_embedding += 1;
}
}
RLI | LRI | FSI => {
levels[i] = top.level;
if let Some(o) = top.over {
classes[i] = o;
}
let rtl = match c {
RLI => true,
LRI => false,
_ => {
let end = matching[i].unwrap_or(n);
first_strong(&original[..end], i + 1) == Some(1)
}
};
let new = if rtl {
next_odd(top.level)
} else {
next_even(top.level)
};
if new <= MAX_DEPTH && overflow_isolate == 0 && overflow_embedding == 0 {
valid_isolate += 1;
stack.push(Entry {
level: new,
over: None,
isolate: true,
});
} else {
overflow_isolate += 1;
}
}
PDI => {
if overflow_isolate > 0 {
overflow_isolate -= 1;
} else if valid_isolate > 0 {
overflow_embedding = 0;
while stack.last().is_some_and(|e| !e.isolate) {
stack.pop();
}
stack.pop();
valid_isolate -= 1;
}
let top = *stack.last().unwrap();
levels[i] = top.level;
if let Some(o) = top.over {
classes[i] = o;
}
}
PDF => {
if overflow_isolate > 0 {
} else if overflow_embedding > 0 {
overflow_embedding -= 1;
} else if !top.isolate && stack.len() >= 2 {
stack.pop();
}
levels[i] = top.level;
}
B => levels[i] = para,
BN => levels[i] = top.level,
_ => {
levels[i] = top.level;
if let Some(o) = top.over {
classes[i] = o;
}
}
}
}
// X9: removed characters are passed over from here on.
let gone: Vec<bool> = original.iter().map(|&c| removed(c)).collect();
// X10: level runs, chained into isolating run sequences.
let mut runs: Vec<Vec<usize>> = Vec::new();
let mut last_level = None;
for i in (0..n).filter(|&i| !gone[i]) {
if last_level == Some(levels[i]) {
runs.last_mut().unwrap().push(i);
} else {
runs.push(vec![i]);
last_level = Some(levels[i]);
}
}
let mut run_of = vec![usize::MAX; n];
for (r, run) in runs.iter().enumerate() {
for &i in run {
run_of[i] = r;
}
}
let mut sequences: Vec<Vec<usize>> = Vec::new();
for (r, run) in runs.iter().enumerate() {
let first = run[0];
// A run that starts with a PDI matching an initiator continues
// that initiator's sequence.
if original[first] == PDI && matching.contains(&Some(first)) {
continue;
}
let mut seq = Vec::new();
let mut r = r;
loop {
seq.extend_from_slice(&runs[r]);
let last = *runs[r].last().unwrap();
match (isolate_initiator(original[last]), matching[last]) {
(true, Some(pdi)) if run_of[pdi] != usize::MAX => r = run_of[pdi],
_ => break,
}
}
sequences.push(seq);
}
for seq in &sequences {
resolve_sequence(seq, chars, original, &mut classes, &levels, &gone, para);
}
// I1–I2.
for i in (0..n).filter(|&i| !gone[i]) {
let l = levels[i];
levels[i] = match (l % 2, classes[i]) {
(0, R) => l + 1,
(0, AN | EN) => l + 2,
(1, L | EN | AN) => l + 1,
_ => l,
};
}
// L1: separators, and whitespace before them or at the end, at the
// paragraph's level.
let mut trailing = true;
for i in (0..n).rev() {
let c = original[i];
if matches!(c, S | B) {
levels[i] = para;
trailing = true;
} else if matches!(c, WS | LRI | RLI | FSI | PDI) || gone[i] {
if trailing {
levels[i] = para;
}
} else {
trailing = false;
}
}
// A removed character takes the level of the one before it.
for i in 0..n {
if gone[i] && !(trailing_at(original, &gone, i)) {
levels[i] = if i == 0 { para } else { levels[i - 1] };
}
}
Paragraph {
level: para,
levels,
removed: gone,
}
}
/// Whether removed character `i` is in the whitespace L1 put at the
/// paragraph's level (before a separator or at the end).
fn trailing_at(original: &[Class], gone: &[bool], i: usize) -> bool {
for k in i + 1..original.len() {
let c = original[k];
if matches!(c, S | B) {
return true;
}
if !(matches!(c, WS | LRI | RLI | FSI | PDI) || gone[k]) {
return false;
}
}
true
}
/// W1–W7 and N0–N2 over one isolating run sequence.
fn resolve_sequence(
seq: &[usize],
chars: &[u32],
original: &[Class],
classes: &mut [Class],
levels: &[u8],
gone: &[bool],
para: u8,
) {
let level = levels[seq[0]];
let dir = |l: u8| if l.is_multiple_of(2) { L } else { R };
// sos and eos: the higher of this level and the one beside it.
let first = seq[0];
let before = (0..first).rev().find(|&i| !gone[i]).map_or(para, |i| levels[i]);
let sos = dir(level.max(before));
let last = *seq.last().unwrap();
// After an isolate initiator (one with no PDI: else the sequence
// would go on), the paragraph's level.
let after = if isolate_initiator(original[last]) {
para
} else {
(last + 1..original.len())
.find(|&i| !gone[i])
.map_or(para, |i| levels[i])
};
let eos = dir(level.max(after));
let mut t: Vec<Class> = seq.iter().map(|&i| classes[i]).collect();
let m = t.len();
// W1.
for k in 0..m {
if t[k] == NSM {
t[k] = if k == 0 {
sos
} else if matches!(original[seq[k - 1]], LRI | RLI | FSI | PDI) {
ON
} else {
t[k - 1]
};
}
}
// W2 and W3.
let mut strong = sos;
for c in t.iter_mut() {
match *c {
L | R => strong = *c,
AL => {
strong = AL;
*c = R;
}
EN if strong == AL => *c = AN,
_ => {}
}
}
// W4.
for k in 1..m.saturating_sub(1) {
match (t[k - 1], t[k], t[k + 1]) {
(EN, ES, EN) => t[k] = EN,
(EN, CS, EN) => t[k] = EN,
(AN, CS, AN) => t[k] = AN,
_ => {}
}
}
// W5.
let mut k = 0;
while k < m {
if t[k] == ET {
let start = k;
while k < m && t[k] == ET {
k += 1;
}
let touches = (start > 0 && t[start - 1] == EN) || (k < m && t[k] == EN);
if touches {
t[start..k].fill(EN);
}
} else {
k += 1;
}
}
// W6.
for c in t.iter_mut() {
if matches!(*c, ES | ET | CS) {
*c = ON;
}
}
// W7.
let mut strong = sos;
for c in t.iter_mut() {
match *c {
L | R => strong = *c,
EN if strong == L => *c = L,
_ => {}
}
}
// N0: paired brackets.
let e = dir(level);
let pairs = bracket_pairs(seq, chars, &t);
for (open, close) in pairs {
let mut found_e = false;
let mut found_other = false;
for c in &t[open + 1..close] {
let s = match *c {
L => Some(L),
R | EN | AN => Some(R),
_ => None,
};
match s {
Some(s) if s == e => found_e = true,
Some(_) => found_other = true,
None => {}
}
}
let set = if found_e {
Some(e)
} else if found_other {
let context = t[..open]
.iter()
.rev()
.find_map(|c| match *c {
L => Some(L),
R | EN | AN => Some(R),
_ => None,
})
.unwrap_or(sos);
Some(if context != e { context } else { e })
} else {
None
};
if let Some(s) = set {
t[open] = s;
t[close] = s;
// NSMs after a bracket take its new type.
for b in [open, close] {
let mut k = b + 1;
while k < m && original[seq[k]] == NSM {
t[k] = s;
k += 1;
}
}
}
}
// N1 and N2.
let neutral = |c: Class| matches!(c, B | S | WS | ON | LRI | RLI | FSI | PDI);
let mut k = 0;
while k < m {
if !neutral(t[k]) {
k += 1;
continue;
}
let start = k;
while k < m && neutral(t[k]) {
k += 1;
}
let side = |c: Class| match c {
L => L,
_ => R,
};
let prev = if start == 0 { sos } else { side(t[start - 1]) };
let next = if k == m { eos } else { side(t[k]) };
let s = if prev == next { prev } else { e };
t[start..k].fill(s);
}
for (k, &i) in seq.iter().enumerate() {
classes[i] = t[k];
}
}
/// BD16: the paired brackets in a sequence, as places in it, by their
/// opening bracket's place.
fn bracket_pairs(seq: &[usize], chars: &[u32], t: &[Class]) -> Vec<(usize, usize)> {
let mut pairs = Vec::new();
let mut stack: Vec<(u32, usize)> = Vec::new();
for (k, &i) in seq.iter().enumerate() {
if t[k] != ON {
continue;
}
let c = chars[i];
let found = tables::BRACKETS.partition_point(|&(a, _, _)| a < c);
let Some(&(_, pair, open)) = tables::BRACKETS.get(found).filter(|&&(a, _, _)| a == c) else {
continue;
};
if open == 1 {
if stack.len() >= 63 {
break;
}
stack.push((canonical(pair), k));
} else if let Some(p) = stack.iter().rposition(|&(want, _)| want == canonical(c)) {
pairs.push((stack[p].1, k));
stack.truncate(p);
}
}
pairs.sort_unstable();
pairs
}
/// U+2329 and U+232A are the same brackets as U+3008 and U+3009.
fn canonical(c: u32) -> u32 {
match c {
0x2329 => 0x3008,
0x232a => 0x3009,
c => c,
}
}
/// The order to draw a line in: indices into it, left to right, removed
/// characters left out (L2).
pub fn visual_order(levels: &[u8], removed: &[bool]) -> Vec<usize> {
let mut order: Vec<usize> = (0..levels.len()).collect();
let Some(&high) = levels.iter().max() else {
return order;
};
let low_odd = levels
.iter()
.copied()
.filter(|l| l % 2 == 1)
.min()
.unwrap_or(high + 1);
let mut l = high;
while l >= low_odd && l > 0 {
let mut k = 0;
while k < order.len() {
if levels[order[k]] >= l {
let start = k;
while k < order.len() && levels[order[k]] >= l {
k += 1;
}
order[start..k].reverse();
} else {
k += 1;
}
}
l -= 1;
}
order.retain(|&i| !removed[i]);
order
}