text_scripts

source of unicode::bidi

1// The Unicode Bidirectional Algorithm, UAX #9 (Unicode 16.0): a2// paragraph's embedding levels from its characters' Bidi_Class (P2-P3,3// explicit embeddings, overrides and isolates X1-X10, weak types W1-W7,4// paired brackets N0, neutrals N1-N2, implicit levels I1-I2), a line's5// whitespace back at the paragraph's level (L1) and its visual order6// (L2). Unicode's BidiTest.txt and BidiCharacterTest.txt check it7// (conformance.alloy).89import std::vector;10import std::option;11import std::sort;1213import pkg::alloy::text::unicode::tables;14import pkg::alloy::text::unicode::properties;15import script_tables;16import script_properties;1718// The deepest explicit embedding level (BD2).19const MAX_DEPTH: u8 = 125;20// The deepest nesting of paired brackets looked at (BD16).21const MAX_BRACKETS: u64 = 63;2223// A paragraph's level and each of its characters' (a character X924// removes taking the level of the one before it).25pub type BidiLevels = struct {26    pub paragraph: u8,27    pub levels: Vector<u8>,28};2930pub fn is_strong(c: BidiClass) -> bool => c is ::L || c is ::R || c is ::AL;3132pub fn is_isolate_initiator(c: BidiClass) -> bool => c is ::LRI || c is ::RLI || c is ::FSI;3334// Whether X9 removes the class: embeddings, overrides, PDF and BN.35pub fn is_removed(c: BidiClass) -> bool => match (c) {36    ::LRE, ::RLE, ::LRO, ::RLO, ::PDF, ::BN true;37    else false;38};3940// Whether L1 takes the class back to the paragraph's level at a line's41// end and before a segment separator: whitespace, isolates, and what X942// removes.43fn is_whitespace(c: BidiClass) -> bool => match (c) {44    ::WS, ::LRI, ::RLI, ::FSI, ::PDI, ::LRE, ::RLE, ::LRO, ::RLO, ::PDF, ::BN true;45    else false;46};4748// The level P2 and P3 give the characters from `start` to `end`, by the49// first strong one outside isolates; None where there is none.50pub fn first_strong_level(classes: &[BidiClass], start: u64, end: u64) -> Option<u8> {51    var depth: u64 = 0;52    for (classes[start..end]) |c| {53        match (c) {54            ::L {55                if (depth == 0) {56                    return ::Some(0);57                }58            }59            ::R, ::AL {60                if (depth == 0) {61                    return ::Some(1);62                }63            }64            ::LRI, ::RLI, ::FSI {65                depth += 1;66            }67            ::PDI {68                if (depth > 0) {69                    depth -= 1;70                }71            }72            ::B {73                return ::None;74            }75            else {}76        }77    }78    return ::None;79}8081// The levels of the characters, given their classes and, for paired82// brackets, their code points (none when only the classes are known);83// paragraphs end after each paragraph separator, each at `level`, or at84// the level of its first strong character with None (`fallback` without85// one, 0 by P3 and 1 as a higher protocol may make it, HL1).86pub fn bidi_levels(87    classes: &[BidiClass],88    chars: &[u32],89    level: Option<u8>,90    fallback: u891) -> BidiLevels {92    var out = BidiLevels {93        .paragraph = level.unwrap_or(fallback),94        .levels = Vector<u8>::with_capacity(classes.length())95    };96    var start: u64 = 0;97    while (start < classes.length()) {98        var end = start;99        while (end < classes.length() && !(classes[end] is ::B)) {100            end += 1;101        }102        end = min(end + 1, classes.length());103        const paragraph = if (level is ::Some |l|) l else first_strong_level(104            &classes,105            start,106            end107        ).unwrap_or(fallback);108        if (start == 0) {109            out.paragraph = paragraph;110        }111        const brackets = if (chars.length() == 0) &chars else &chars[start..end];112        out.levels.append(&paragraph_levels(&classes[start..end], &brackets, paragraph).view());113        start = end;114    }115    return move out;116}117118fn min(a: u64, b: u64) -> u64 => if (a < b) a else b;119120// What an explicit embedding or override sets.121type Override = enum {122    Neutral,123    LeftToRight,124    RightToLeft,125};126127// An entry of the directional status stack (X1).128type Status = struct {129    level: u8,130    override: Override,131    isolate: bool,132};133134// A paragraph's work: its classes as the rules change them, its levels,135// and its isolates' matching PDIs.136type Paragraph = struct {137    original: &[BidiClass],138    chars: &[u32],139    level: u8,140    types: Vector<BidiClass>,141    levels: Vector<u8>,142    explicit: Vector<u8>, // the levels X1-X8 give, which sos and eos read143    matching: Vector<u32>, // an isolate initiator's PDI, NONE without one144    matched: Vector<bool>, // whether a PDI matches an initiator145};146147const NONE: u32 = 0xFFFFFFFF;148149fn paragraph_levels(classes: &[BidiClass], chars: &[u32], level: u8) -> Vector<u8> {150    var p = Paragraph {151        .original = &classes,152        .chars = &chars,153        .level = level,154        .types = Vector<BidiClass>::from(&classes),155        .levels = Vector<u8>::filled(level, classes.length()),156        .explicit = Vector<u8>::empty(),157        .matching = Vector<u32>::filled(NONE, classes.length()),158        .matched = Vector<bool>::filled(false, classes.length())159    };160    p.match_isolates();161    p.explicit_levels();162    p.explicit = copy p.levels;163    p.resolve_sequences();164    // what X9 removed takes the level before it165    var before = level;166    for (classes, p.levels.items()) |c, &var l| {167        if (is_removed(c)) {168            l = before;169        }170        before = l;171    }172    return move p.levels;173}174175// BD9: each isolate initiator's matching PDI.176fn match_isolates(self p: &var Paragraph) {177    var open = Vector<u32>::empty();178    for (p.original, [..p.original.length()]) |c, i| {179        if (is_isolate_initiator(c)) {180            open.push(i to u32);181        } else if (c is ::PDI) {182            if (open.pop() is ::Some |initiator|) {183                p.matching.get_var(initiator to u64) = i to u32;184                p.matched.get_var(i) = true;185            }186        }187    }188}189190// X1-X8: the levels embeddings, overrides and isolates give, overrides191// changing the classes they cover.192fn explicit_levels(self p: &var Paragraph) {193    var stack = Vector<Status>::with_capacity(MAX_DEPTH to u64 + 2);194    stack.push(Status { .level = p.level, .override = Override::Neutral, .isolate = false });195    var overflow_isolates: u64 = 0;196    var overflow_embeddings: u64 = 0;197    var valid_isolates: u64 = 0;198    for ([..p.original.length()]) |i| {199        const c = p.original[i];200        match (c) {201            ::RLE, ::LRE, ::RLO, ::LRO {202                const top = stack.last();203                p.levels.get_var(i) = top.level;204                const odd = c is ::RLE || c is ::RLO;205                const next = next_level(top.level, odd);206                if (next <= MAX_DEPTH && overflow_isolates == 0 && overflow_embeddings == 0) {207                    stack.push(Status {208                        .level = next,209                        .override = match (c) {210                            ::RLO Override::RightToLeft;211                            ::LRO Override::LeftToRight;212                            else Override::Neutral;213                        },214                        .isolate = false215                    });216                } else if (overflow_isolates == 0) {217                    overflow_embeddings += 1;218                }219            }220            ::RLI, ::LRI, ::FSI {221                const top = stack.last();222                p.levels.get_var(i) = top.level;223                p.overridden(i, top.override);224                var odd = c is ::RLI;225                if (c is ::FSI) {226                    const end = if (p.matching.get(i) != NONE) p.matching.get(227                        i228                    ) to u64 else p.original.length();229                    odd = first_strong_level(&p.original, i + 1, end).unwrap_or(0) == 1;230                }231                const next = next_level(top.level, odd);232                if (next <= MAX_DEPTH && overflow_isolates == 0 && overflow_embeddings == 0) {233                    valid_isolates += 1;234                    stack.push(Status {235                        .level = next,236                        .override = Override::Neutral,237                        .isolate = true238                    });239                } else {240                    overflow_isolates += 1;241                }242            }243            ::PDI {244                if (overflow_isolates > 0) {245                    overflow_isolates -= 1;246                } else if (valid_isolates > 0) {247                    overflow_embeddings = 0;248                    while (!stack.last().isolate) {249                        stack.pop();250                    }251                    stack.pop();252                    valid_isolates -= 1;253                }254                const top = stack.last();255                p.levels.get_var(i) = top.level;256                p.overridden(i, top.override);257            }258            ::PDF {259                if (overflow_isolates > 0) {} else if (overflow_embeddings > 0) {260                    overflow_embeddings -= 1;261                } else if (!stack.last().isolate && stack.length() >= 2) {262                    stack.pop();263                }264                p.levels.get_var(i) = stack.last().level;265            }266            ::B {267                p.levels.get_var(i) = p.level;268            }269            ::BN {270                p.levels.get_var(i) = stack.last().level;271            }272            else {273                const top = stack.last();274                p.levels.get_var(i) = top.level;275                p.overridden(i, top.override);276            }277        }278    }279}280281// The least level above `level`, odd or even.282fn next_level(level: u8, odd: bool) -> u8 {283    const up = level + 1;284    return if ((up % 2 == 1) == odd) up else up + 1;285}286287// The character's class as the override in force makes it.288fn overridden(self p: &var Paragraph, i: u64, override: Override) {289    match (override) {290        ::LeftToRight {291            p.types.get_var(i) = BidiClass::L;292        }293        ::RightToLeft {294            p.types.get_var(i) = BidiClass::R;295        }296        ::Neutral {}297    }298}299300// X10: the isolating run sequences, each resolved by W1-I2.301fn resolve_sequences(self p: &var Paragraph) {302    // the characters X9 keeps, and the level runs among them303    var kept = Vector<u32>::with_capacity(p.original.length());304    for (p.original, [..p.original.length()]) |c, i| {305        if (!is_removed(c)) {306            kept.push(i to u32);307        }308    }309    var runs = Vector<[u64 : 2]>::empty(); // ranges of `kept`310    var run_of = Vector<u32>::filled(NONE, p.original.length()); // a run's first character's311    var k: u64 = 0;312    while (k < kept.length()) {313        const level = p.levels.get(kept.get(k) to u64);314        var end = k + 1;315        while (end < kept.length() && p.levels.get(kept.get(end) to u64) == level) {316            end += 1;317        }318        run_of.get_var(kept.get(k) to u64) = runs.length() to u32;319        runs.push([k, end]);320        k = end;321    }322    var sequence = Vector<u32>::empty();323    for (runs.view()) |run| {324        const first = kept.get(run[0]) to u64;325        if (p.original[first] is ::PDI && p.matched.get(first)) {326            continue; // the end of an isolate, which its initiator's sequence takes327        }328        sequence.clear();329        var r = run;330        while (true) {331            sequence.append(&kept.view()[r[0]..r[1]]);332            const last = sequence.last() to u64;333            const pdi = p.matching.get(last);334            if (!is_isolate_initiator(p.original[last]) || pdi == NONE) {335                break;336            }337            const next = run_of.get(pdi to u64);338            if (next == NONE) {339                break;340            }341            r = runs.get(next to u64);342        }343        p.resolve(&sequence.view(), &kept.view());344    }345}346347// The direction of a level: L even, R odd.348fn direction(level: u8) -> BidiClass => if (level % 2 == 0) BidiClass::L else BidiClass::R;349350// The strong direction a resolved class counts as for N0 and N1: L, or R351// for R and the numbers; None for a neutral.352fn strong_direction(c: BidiClass) -> Option<BidiClass> => match (c) {353    ::L ::Some(BidiClass::L);354    ::R, ::AL, ::EN, ::AN ::Some(BidiClass::R);355    else ::None;356};357358// Whether a resolved class is a neutral or an isolate formatting359// character (NI).360fn is_neutral(c: BidiClass) -> bool => match (c) {361    ::B, ::S, ::WS, ::ON, ::LRI, ::RLI, ::FSI, ::PDI true;362    else false;363};364365// The level of the kept character before or after the sequence's, the366// paragraph's at its ends.367fn neighbour_level(self p: &Paragraph, kept: &[u32], at: u32, after: bool) -> u8 {368    // the kept characters are in order: find `at` among them369    var low: u64 = 0;370    var high = kept.length();371    while (low < high) {372        const middle = (low + high) / 2;373        if (kept[middle] < at) {374            low = middle + 1;375        } else {376            high = middle;377        }378    }379    if (after) {380        return if (low + 1 < kept.length()) p.explicit.get(kept[low + 1] to u64) else p.level;381    }382    return if (low > 0) p.explicit.get(kept[low - 1] to u64) else p.level;383}384385// W1-I2 over an isolating run sequence.386fn resolve(self p: &var Paragraph, sequence: &[u32], kept: &[u32]) {387    const n = sequence.length();388    const level = p.levels.get(sequence[0] to u64);389    const before = p.neighbour_level(&kept, sequence[0], false);390    const last = sequence[n - 1];391    const after = if (is_isolate_initiator(p.original[last to u64])) p.level else p.neighbour_level(392        &kept,393        last,394        true395    );396    const sos = direction(if (before > level) before else level);397    const eos = direction(if (after > level) after else level);398    // the sequence's classes, as the rules change them399    var t = Vector<BidiClass>::with_capacity(n);400    for (sequence) |i| {401        t.push(p.types.get(i to u64));402    }403    const types = &var t.items();404    var explicit = Vector<bool>::with_capacity(n); // NSM before W1405    for (types) |c| {406        explicit.push(c is ::NSM);407    }408    // W1: a mark takes the class before it, ON after an isolate409    var previous = sos;410    for (types) |&var c| {411        if (c is ::NSM) {412            c = previous;413        } else if (is_isolate_initiator(c) || c is ::PDI) {414            previous = BidiClass::ON;415            continue;416        }417        previous = c;418    }419    // W2, W3: a European number after Arabic letters is an Arabic one;420    // Arabic letters are R421    var strong = sos;422    for (types) |&var c| {423        match (c) {424            ::L, ::R {425                strong = c;426            }427            ::AL {428                strong = c;429                c = BidiClass::R;430            }431            ::EN {432                if (strong is ::AL) {433                    c = BidiClass::AN;434                }435            }436            else {}437        }438    }439    // W4: a single separator between two numbers of a kind440    if (n >= 3) {441        for ([1..n - 1]) |k| {442            const c = types[k];443            const a = types[k - 1];444            const b = types[k + 1];445            if ((c is ::ES || c is ::CS) && a is ::EN && b is ::EN) {446                types[k] = BidiClass::EN;447            } else if (c is ::CS && a is ::AN && b is ::AN) {448                types[k] = BidiClass::AN;449            }450        }451    }452    // W5: terminators next to a European number are one453    var k: u64 = 0;454    while (k < n) {455        if (!(types[k] is ::ET)) {456            k += 1;457            continue;458        }459        var end = k;460        while (end < n && types[end] is ::ET) {461            end += 1;462        }463        if ((k > 0 && types[k - 1] is ::EN) || (end < n && types[end] is ::EN)) {464            for (types[k..end]) |&var c| {465                c = BidiClass::EN;466            }467        }468        k = end;469    }470    // W6, W7: other separators and terminators are neutral; a European471    // number after L is L472    strong = sos;473    for (types) |&var c| {474        match (c) {475            ::ES, ::ET, ::CS {476                c = BidiClass::ON;477            }478            ::L, ::R {479                strong = c;480            }481            ::EN {482                if (strong is ::L) {483                    c = BidiClass::L;484                }485            }486            else {}487        }488    }489    const embedding = direction(level);490    if (p.chars.length() > 0) {491        p.resolve_brackets(&sequence, &var types, &explicit.view(), sos, embedding);492    }493    // N1, N2: neutrals between two of a direction take it, others the494    // embedding's495    k = 0;496    while (k < n) {497        if (!is_neutral(types[k])) {498            k += 1;499            continue;500        }501        var end = k;502        while (end < n && is_neutral(types[end])) {503            end += 1;504        }505        const leading = if (k == 0) sos else strong_direction(types[k - 1]).unwrap_or(embedding);506        const trailing = if (end == n) eos else strong_direction(types[end]).unwrap_or(embedding);507        const resolved = if (leading == trailing) leading else embedding;508        for (types[k..end]) |&var c| {509            c = resolved;510        }511        k = end;512    }513    // I1, I2514    for (sequence, types) |i, c| {515        const l = p.levels.get(i to u64);516        var up: u8 = 0;517        if (l % 2 == 0) {518            up = match (c) {519                ::R 1;520                ::AN, ::EN 2;521                else 0;522            };523        } else if (c is ::L || c is ::EN || c is ::AN) {524            up = 1;525        }526        p.levels.get_var(i to u64) = l + up;527    }528}529530// A canonical equivalent of the bracket's code point, as N0 compares531// them: the angle brackets U+2329 and U+232A are U+3008 and U+3009.532fn canonical_bracket(c: u32) -> u32 => match (c) {533    0x2329 0x3008;534    0x232A 0x3009;535    else c;536};537538// An opening bracket waiting for its closing one (BD16).539type Opening = struct {540    closing: u32,541    at: u64,542};543544// N0: paired brackets take the direction of the strong text inside them,545// or that of the text before them when it is the one inside.546fn resolve_brackets(547    self p: &Paragraph,548    sequence: &[u32],549    types: &var [BidiClass],550    explicit_marks: &[bool],551    sos: BidiClass,552    embedding: BidiClass553) {554    var open = Vector<Opening>::empty();555    var pairs = Vector<[u64 : 2]>::empty();556    for (sequence, [..sequence.length()]) |i, k| {557        if (!(types[k] is ::ON)) {558            continue;559        }560        const c = p.chars[i to u64];561        const b = if (bracket(c) is ::Some |b|) b else {562            continue;563        };564        if (!b.closing) {565            if (open.length() == MAX_BRACKETS) {566                break;567            }568            open.push(Opening { .closing = canonical_bracket(b.other), .at = k });569            continue;570        }571        const closing = canonical_bracket(c);572        var s = open.length();573        while (s > 0) {574            s -= 1;575            if (open.get(s).closing == closing) {576                pairs.push([open.get(s).at, k]);577                open.truncate(s);578                break;579            }580        }581    }582    sort_by(&var pairs.items(), (a, b) => a[0] < b[0]);583    for (pairs.view()) |pair| {584        var inside: Option<BidiClass> = ::None;585        for (types[pair[0] + 1..pair[1]]) |c| {586            if (strong_direction(c) is ::Some |d|) {587                inside = ::Some(d);588                if (d == embedding) {589                    break;590                }591            }592        }593        const found = if (inside is ::Some |d|) d else {594            continue;595        };596        var resolved = embedding;597        if (found != embedding) {598            var context = sos;599            var k = pair[0];600            while (k > 0) {601                k -= 1;602                if (strong_direction(types[k]) is ::Some |d|) {603                    context = d;604                    break;605                }606            }607            if (context != embedding) {608                resolved = context;609            }610        }611        for (pair) |at| {612            types[at] = resolved;613            var next = at + 1;614            while (next < types.length() && explicit_marks[next]) {615                types[next] = resolved;616                next += 1;617            }618        }619    }620}621622// L1 over a line's characters: segment and paragraph separators, and the623// whitespace before them and at the line's end, back at the paragraph's624// level.625pub fn reset_whitespace(classes: &[BidiClass], levels: &var [u8], paragraph: u8) {626    var trailing = true;627    var k = classes.length();628    while (k > 0) {629        k -= 1;630        const c = classes[k];631        if (c is ::S || c is ::B) {632            levels[k] = paragraph;633            trailing = true;634        } else if (trailing && is_whitespace(c)) {635            levels[k] = paragraph;636        } else {637            trailing = false;638        }639    }640}641642// L2: the line's characters in visual order, from the left, by their643// levels: from the highest level down to the lowest odd one, each run644// at that level or above reversed.645pub fn visual_order(levels: &[u8]) -> Vector<u64> {646    var order = Vector<u64>::with_capacity(levels.length());647    var highest: u8 = 0;648    var lowest_odd: u8 = 255;649    for (levels, [..levels.length()]) |l, k| {650        order.push(k);651        if (l > highest) {652            highest = l;653        }654        if (l % 2 == 1 && l < lowest_odd) {655            lowest_odd = l;656        }657    }658    reorder(&var order.items(), &levels, highest, lowest_odd);659    return move order;660}661662// Reverses the runs of `order`, at each level from `highest` down to663// `lowest_odd`, whose items' levels are at that level or above.664pub fn reorder(order: &var [u64], levels: &[u8], highest: u8, lowest_odd: u8) {665    var level = highest;666    while (level >= lowest_odd && level > 0) {667        var k: u64 = 0;668        while (k < order.length()) {669            if (levels[order[k]] < level) {670                k += 1;671                continue;672            }673            var end = k;674            while (end < order.length() && levels[order[end]] >= level) {675                end += 1;676            }677            var a = k;678            var b = end - 1;679            while (a < b) {680                const swapped = order[a];681                order[a] = order[b];682                order[b] = swapped;683                a += 1;684                b -= 1;685            }686            k = end;687        }688        level -= 1;689    }690}